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

标签 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)

最佳答案

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

相关文章:

r - 将相同的组件添加到 ggplots 列表中

r - str_replace(程序包纵梁)不能替换r中的括号?

r - 如何在 R Shiny 中出于调试目的打印 checkboxGroupInput 中的选定值?

r - 从分组单选操作按钮禁用单选单选

javascript - 如何在 Shiny 的应用程序加载时触发 JS 脚本

R:引用类类型的引用类中的字段

amazon-web-services - 须藤: stop: command not found

r - 如何在 Shiny 中读取 csv 文件?

r - 无法使用 Shinyjs() 禁用 Shiny 的应用程序单选按钮

r - 如何在 R 中创建类数组?