如何使用shinyjs一次hide
/show
几个元素?在下面的示例中,我的目标是只用两行代码而不是四行代码来隐藏/显示两个表。我为什么要这样做?实际上,我正在处理多个表和多个事件,以便同时显示/隐藏它们会使代码更清晰。
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
actionButton("hide","Hide!"),
actionButton("show","Show!"),
tableOutput("table1"),
tableOutput("table2"))
server <- function(input, output, session) {
output$table1 <- renderTable({head(iris)})
output$table2 <- renderTable({head(iris)})
observeEvent(input$hide, {hide("table1")})
observeEvent(input$show, {show("table1")})
observeEvent(input$hide, {hide("table2")})
observeEvent(input$show, {show("table2")})}
shinyApp(ui, server)
最佳答案
您可以编写一个函数来执行这两个操作,并为每个要隐藏/显示的 ui 元素调用它们一次。
library(shiny)
library(shinyjs)
toggleView <- function(input, output_name){
observeEvent(input$show, {show(output_name)})
observeEvent(input$hide, {hide(output_name)})
}
ui <- fluidPage(
useShinyjs(),
actionButton("hide","Hide!"),
actionButton("show","Show!"),
tableOutput("table1"),
tableOutput("table2"))
server <- function(input, output, session) {
output$table1 <- renderTable({head(iris)})
output$table2 <- renderTable({head(iris)})
toggleView(input, "table1")
toggleView(input, "table2")
}
shinyApp(ui, server)
您还可以更进一步,根据
output_name
验证此函数。但是,请确保使用 lapply
而不是 for
,因为后者可能会遇到惰性求值的问题。toggleViews <- function(input, output_names){
lapply(output_names, function(output_name){
toggleView(input, output_name)
})
}
...
toggleViews(input, c("table1", "table2"))
关于r - 如何使用shinyjs一次隐藏/显示多个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46733945/