【问题标题】:How to create dynamic number of observeEvent in another observeEvent?如何在另一个observeEvent中创建动态数量的observeEvent?
【发布时间】:2019-01-22 11:50:57
【问题描述】:

Here我问了一个类似的问题并得到了一个有效的答案。但是,如果子段的“actionButton”被“selectInput”替换,则该解决方案不起作用。在每次选择 selectInput 时都会创建两个输出。请帮忙..谢谢....

library(shiny)

ui <- fluidPage(
  verbatimTextOutput("txt",placeholder = T), #"It is Created for Testing"
  actionButton("addSeg", "Add a Segment"),
  uiOutput("myUI")
)

server <- function(input, output, session) {
  alld <- reactiveValues()
  alld$ui <- list()

  # Action to add new Segment
  observeEvent(input$addSeg,{
    new_id <- length(alld$ui) + 1
    sub_name <- paste0("addSub_", new_id)

    alld$ui[[new_id]] <- list(selectInput(sub_name,"Add a variable", choices = c("V1","V2"), selected  = NULL))

    observeEvent(input[[sub_name]], {
      new_text_id <- length(alld$ui[[new_id]]) + 1
      alld$ui[[new_id]][[new_text_id]] <- HTML(paste0("Variable ",input[[sub_name]]," added<br>"))
    }, ignoreInit = TRUE)
  })

  output$myUI <- renderUI({alld$ui})

  output$txt <- renderText({class(alld$ui)})
}

shinyApp(ui, server)

【问题讨论】:

  • 顺便说一句,你为什么要用 selectInput 替换 actionButton?
  • @amrrs 这是一个示例代码。在我原来的闪亮应用程序中需要替换,它更复杂..

标签: r shiny


【解决方案1】:

出现此行为是因为每次将新元素添加到列表时都会重新呈现自定义 UI 元素。单击“V2”并添加新文本元素后,selectInput 本身会重新渲染并重置为 V1,您创建的观察者会注意到这一点。

以下可能是您的解决方案:

  observeEvent(input$addSeg,{
    new_id <- length(alld$ui) + 1
    sub_name <- paste0("addSub_", new_id)

    alld$ui[[new_id]] <- list(
      selectInput(sub_name,
                  "Add a variable",
                  choices = c("", "V1","V2"),
                  selected  = "")
      )

    observeEvent(input[[sub_name]], {
      if (input[[sub_name]] == "") return()
      new_text_id <- length(alld$ui[[new_id]]) + 1
      alld$ui[[new_id]][[new_text_id]] <- HTML(paste0("Variable ",input[[sub_name]]," added<br>"))
    }, ignoreInit = TRUE)
  })

我在这里所做的是向您的selectInputs 添加一个空选项,并向相应的观察者添加一个条件,即如果输入为空,它不应该做任何事情。这样,我利用“重置”行为变得有用而不是烦人。

【讨论】:

  • 如果这解决了您的问题,请标记它已解决@RajaSaha
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 2017-08-03
  • 2021-09-09
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多