如何确保闪亮的应用程序在使用模块时知道当前打开了哪个选项卡?

How to make sure the shiny app knows which tab is currently opened when using modules?

我在闪亮的应用程序中使用模块来显示不同 tabPanel 的内容。我希望能够通过单击一个按钮转到第二个选项卡。我有以下代码:

library(shiny)
library(shinydashboard)

moduleUI <- function(id){

  ns <- NS(id)
  sidebarPanel(
    actionButton(ns("action1"), label = "Go to tab 2")
  )
}

module <- function(input, output, session, openTab){

  observeEvent(input$action1, {
    openTab("two")
  })

  return(openTab)
}

ui <- fluidPage(
  navlistPanel(id = "tabsPanel",
               tabPanel("one", moduleUI("first")),
               tabPanel("two", moduleUI("second"))
  ))

server <- function(input, output, session){
  openTab <- reactiveVal()
  openTab("one")

  openTab <- callModule(module,"first", openTab)
  openTab <- callModule(module,"second", openTab)

  observeEvent(openTab(), {
    updateTabItems(session, "tabsPanel", openTab())
  })
}

shinyApp(ui = ui, server = server)

然而这只有效一次。我认为的问题是模块不知道应用程序中的选项卡何时更改。因此,我正在寻找一种方法来确保模块知道打开了哪个选项卡,以便 actionButton 工作更多次。 我考虑过使用 input$tabsPanel 但我不知道如何实现它。 帮助将不胜感激。

问题是一旦用户手动切换回选项卡 1,openTab() 不会更新。因此,当您第二次单击 actionButton 时,openTab 从 "two" 更改为 "two"(即保持不变),因此不会触发您的 observeEvent。

您可以添加:

  observeEvent(input$tabsPanel,{
    openTab(input$tabsPanel)
  })

因此,当用户手动更改回 tab1(或任何其他选项卡)时,openTab reactiveVal 也会更新。


顺便说一句,您不需要模块来执行您想要的操作,但我假设您有特定的理由使用它们。对于其他想要实现相同但不需要模块的人:

library(shiny)
library(shinydashboard) 

ui <- fluidPage(
  sidebarPanel(
    actionButton(ns("action1"), label = "Go to tab 2")),
  navlistPanel(id = "tabsPanel",
               tabPanel("one"),
               tabPanel("two")
  ))

server <- function(input, output, session){ 
  observeEvent(input$action1, {
    updateTabItems(session, "tabsPanel", "two")
  })
}

shinyApp(ui = ui, server = server)