gpt4 book ai didi

r - 如何使用removeUI删除元素后清理 "input"

转载 作者:行者123 更新时间:2023-12-01 18:58:48 27 4
gpt4 key购买 nike

如何在删除某些元素后清理“输入”(下面示例中的 verbatimTextOutput("summary"))。我尝试使用 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)

知道如何做到这一点吗?

最佳答案

您可以使用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)

希望这有帮助!!

关于r - 如何使用removeUI删除元素后清理 "input",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51002240/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com