如何避免R Shiny中重复的insertUI?

时间:2019-05-07 23:06:37

标签: r shiny

在此代码中

if (interactive()) {
  # Define UI
  ui <- fluidPage(
    actionButton("add", "Add UI"),
    actionButton("remove", "Remove UI"),
    tags$div(id = "add")
  )

  # Server logic
  server <- function(input, output, session) {

    # adding UI
    observeEvent(input$add, {
      insertUI(
        selector = "#add",
        where = "afterEnd",
        ui = 
          div(
            textInput("txt", "Insert some text"),
            id="textinput"
          )
      )
    })

    # removing UI
    observeEvent(input$remove, {
      removeUI(selector = "#textinput")
    })
  }

  shinyApp(ui, server)
}

我希望动态UI仅一次出现。 无论按下“添加”按钮的次数。

但是,单击“删除UI”按钮后,您应该能够再次添加动态界面(也是一次)

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用<ul id="list"> <li id="1">Item 1</li> <li id="2">Item 2</li> <li id="3">Item 3</li> </ul>conditionalPanel来做到这一点。

observe

编辑-不使用library(shiny) if (interactive()) { # Define UI ui <- fluidPage( actionButton("add", "Add UI"), actionButton("remove", "Remove UI"), conditionalPanel(condition = "input.add > 0", uiOutput("textbox")) ) # Server logic server <- function(input, output, session) { # adding UI observe({ if (!is.null(input$add)) { output$textbox <- renderUI({ div( textInput("txt", "Insert some text"), id="textinput" ) }) } }) # removing UI observeEvent(input$remove, { removeUI(selector = "#textinput") }) } shinyApp(ui, server) }

conditionalPanel