根据 R Shiny 上的活动选项卡创建反应变量

Create a reactive variable depending on active Tab on R Shiny

我有这个简单的应用程序,我希望能够“捕获”活动选项卡。 例如,如果我在“tab1”上,我在顶部的 selectInput 将是 c(“a”,“b”,“c”),但如果我在另一个选项卡上,它会改变 我想创建一个动态变量 active_tab,但我不知道该怎么做。

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)


shinyApp(
  ui = dashboardPage(
    title="Shiny Dashboard",
    header = shinydashboardPlus::dashboardHeader(
      title = "Example",
      leftUi = tagList(
        uiOutput("reactive_ui")
      )),
    
    sidebar = dashboardSidebar(
      sidebarMenu(
        menuItem("tab1",tabName = "tab1"),
        menuItem("tab2",tabName = "tab2")
      )
    ),
    body = dashboardBody(
      tabItems(
        tabItem("tab1"),
        tabItem("tab2")
      )
    )
  ),
  
  server = function(input, output) {
    output$reactive_ui =renderUI({
      if (active_tab == "tab1") choice = c("a","b","c","d") 
      if (active_tab == "tab2") choice = c("e","f","g")
      
      selectInput("select", NULL,choices = choice )
    })
  }
)


 

sidebarMenu 包含一个 id 参数,可用于检索服务器端活动选项卡的名称。

如果只是 selectInput 您想要更新选项卡更改,请查看 updateSelectInput 以便您可以更新选项而无需 re-render每次标签更改时输入。这也意味着输入在应用程序打开后定义。

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)

shinyApp(
  ui = dashboardPage(
    title = "Shiny Dashboard",
    header = shinydashboardPlus::dashboardHeader(
      title = "Example",
      leftUi = tagList(
        selectInput("select", NULL, choices = c("a", "b", "c", "d"))
      )
    ),
    
    sidebar = dashboardSidebar(
      sidebarMenu(
        id = "tab",
        menuItem("tab1", tabName = "tab1"),
        menuItem("tab2", tabName = "tab2")
      )
    ),
    body = dashboardBody(
      tabItems(
        tabItem("tab1"),
        tabItem("tab2")
      )
    )
  ),
  
  server = function(input, output, session) {
    observeEvent(input$tab, {
      if (input$tab == "tab1") {
        choices <- c("a", "b", "c", "d")
      } else if (input$tab == "tab2") {
        choices <- c("e", "f", "g")
      }
      updateSelectInput(session, "select", choices = choices)
    })
  }
)