如何使用shinyjs同时隐藏/显示多个元素?

Joe*_*Joe 5 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)
Run Code Online (Sandbox Code Playgroud)

Gre*_*lia 4

您可以编写一个执行这两种操作的函数,并为每个要隐藏/显示的 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)
Run Code Online (Sandbox Code Playgroud)

您还可以更进一步,根据 验证此函数output_name。确保使用lapply而不是for但是,因为后者可能会遇到惰性求值的问题。

toggleViews <- function(input, output_names){
  lapply(output_names, function(output_name){
    toggleView(input, output_name)
  })
}

...

toggleViews(input, c("table1", "table2"))
Run Code Online (Sandbox Code Playgroud)

  • 如果您在服务器内部定义“toggleView”函数,则不需要“input”参数。或者,您也可以使用“input = getDefaultReactiveDomain()$input”进行一些环境黑客攻击 (2认同)