如何使用shinyjs一次隐藏/显示多个元素?

时间:2017-10-13 16:06:24

标签: r shiny shinyjs

如何使用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)

1 个答案:

答案 0 :(得分:3)

您可以编写一个执行这两个操作的函数,并为每个要隐藏/显示的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"))
相关问题