使用removeUI删除元素后如何清理"输入"

Vin*_*der 5 r shiny

删除一些元素后,如何清除"输入" (下面的示例中的verbatimTextOutput("摘要")).我尝试了一些shiny.unbindAll没有成功的东西.专职人员removeUI不做这项工作.请看一下这个例子:

library(shiny)

ui <- fluidPage(

    actionButton('insertBtn', 'Insert'), 
    actionButton('removeBtn', 'Remove'), 
    verbatimTextOutput("summary"),
    tags$div(id = 'placeholder') 

)

server <- function(input, output, session) {
  ## keep track of elements inserted and not yet removed
  inserted <- c()

  observeEvent(input$insertBtn, {
    btn <- input$insertBtn
    id <- paste0('txt', btn)
    insertUI(
      selector = '#placeholder',
      ## wrap element in a div with id for ease of removal
      ui = tags$div(
        actionButton(inputId = paste0("truc",id),label = paste0("truc",id)), 
        id = id
      )
    )
    inserted <<- c(id, inserted)
  })

  observeEvent(input$removeBtn, {
    removeUI(
      ## pass in appropriate div id
      selector = paste0('#', inserted[length(inserted)])
    )
    inserted <<- inserted[-length(inserted)]
  })


  output$summary <- renderPrint({
    invalidateLater(1000)
    lst <- reactiveValuesToList(input) 
    message("upd")
    lst[order(names(lst))]
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

知道怎么做吗?

小智 4

您可以使用shinyjs来修改输入。像这样的东西会起作用吗?

library(shiny)
library(shinyjs)

ui <- fluidPage(

  actionButton('insertBtn', 'Insert'), 
  actionButton('removeBtn', 'Remove'), 
  verbatimTextOutput("summary"),
  tags$div(id = 'placeholder'), 
  useShinyjs()

)

server <- function(input, output, session) {
  ## keep track of elements inserted and not yet removed
  inserted <- c()

  observeEvent(input$insertBtn, {
    btn <- input$insertBtn
    id <- paste0('txt', btn)
    insertUI(
      selector = '#placeholder',
      ## wrap element in a div with id for ease of removal
      ui = tags$div(
        actionButton(inputId = paste0("truc",id),label = paste0("truc",id)), 
        id = id
      )
    )
    inserted <<- c(id, inserted)
  })

  observeEvent(input$removeBtn, {
    id <- inserted[length(inserted)]
    removeUI(
      ## pass in appropriate div id
      selector = paste0('#',id)
    )
    #use the javascript functio Shiny.onInputChange to set the values of 
    # the removed inputs to NULL, javascript uses lower case for null
    runjs(paste0("Shiny.onInputChange('",paste0("truc",id),"',null)"))
    inserted <<- inserted[-length(inserted)]
  })


  output$summary <- renderPrint({
    invalidateLater(1000)
    lst <- reactiveValuesToList(input) 
    message("upd")
    lst[order(names(lst))]
  })
}

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!!