闪亮:点击按钮时添加新元素

5

我想在模态对话框中使用textInput和textAreaInput打印一个tagList()。

然后,在这个模态对话框中,我要通过点击“+”图标添加一个带有textInput和textAreaInput的新元素,将ID编号增加到1。

当模态对话框出现时,第一个元素(ID为0)可以通过tagAppendChild很好地创建,但是单击“+”图标不会使用observeEvent和tagAppendChild在我的定义的tagList上添加第二个元素。

以下是可重现的Shiny代码。

有什么线索吗?谢谢

ui <- fluidPage(   
        actionButton("open", "Modal") 
    )

server <- function(input, output, session) {   
    count <- reactiveVal(0) 
    my_list <- tagList()   
    observeEvent(input$open, {
        count(0)
        showModal(modalDialog(
          tagAppendChild(my_list, add_item(count())),
          actionButton(inputId = "add_entry", style = "border: 0px", label = NULL, icon("circle-plus")),
          footer = tagList(modalButton("Cancel"), actionButton("Ok", "OK"))
        ))   
    })

  add_item <- function(count) {
    return(
      tagList(
        textInput(width=164, paste0("add_id",count), paste("ID", count()), placeholder="Only numbers allowed"),
        textAreaInput(width=400, height=100, paste0("add_comment",count), "Comments")
      )
    )   
  }

  observeEvent(input$add_entry, {
    count(count()+1)
    tagAppendChild(my_list, add_item(count()))   
  }) 
}


shinyApp(ui, server)
1个回答

6
我们可以使用shiny::insertUI来实现这一点。在这里,我创建了一个具有"id"为"modal_ui"的div,它将告诉insertUI我想要插入ui的位置。请注意保留html标签。
  observeEvent(input$add_entry, {
    count(count() + 1)
    insertUI(selector = "#modal_ui", ui = add_item(count()))
  })

应用:

library(shiny)

ui <- fluidPage(
  actionButton("open", "Modal")
)

server <- function(input, output, session) {
  count <- reactiveVal(0)
  my_list <- tagList()
  observeEvent(input$open, {
    count(0)
    showModal(
      modalDialog(
        div(
          id = "modal_ui",
          add_item(count())
        ),
        actionButton(
          inputId = "add_entry",
          style   = "border: 0px",
          label   = NULL,
          icon("circle-plus")
        ),
        footer = tagList(modalButton("Cancel"), actionButton("Ok", "OK"))
      )
    )
  })

  add_item <- function(count) {
    div(
      id = paste0("div_", count),
      textInput(
        inputId     = paste0("add_id", count),
        label       = paste("ID", count()),
        width       = 164,
        placeholder = "Only numbers allowed"
      ),
      textAreaInput(width = 400, height = 100, paste0("add_comment", count), "Comments")
    )
  }

  observeEvent(input$add_entry, {
    count(count() + 1)
    insertUI(selector = "#modal_ui", ui = add_item(count()))
  })
}


shinyApp(ui, server)

enter image description here


太好了!谢谢,它像魔法一样运行,我不记得有insertUI存在,知道这个是件好事! - Fabrice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接