仅当用户单击 tabPanel 时才动态渲染 dashboardSidebar

Render dashboardSidebar dynamically only when user clicks tabPanel

我正在尝试在单击 tabPanel 时动态呈现 dashboardSidebar,以便在应用程序初始化时不会加载所有选项卡上的控件。为此,我创建了一个函数 load_tab2 但此函数不会在选项卡上单击时呈现任何内容。有人可以指出以下代码的问题吗?

library(shiny)
library(shinydashboard)

sidebar <- dashboardSidebar(
  collapsed = FALSE,
  sidebarMenu(
    id = "menu_sidebar",
    conditionalPanel(
      condition = "input.main_tab == 'tab_1'",
      selectizeInput(inputId = "t1", label = "Select by:", choices = c(as.character(30:40))),
      div("Hello Tab 1")
    ))
)

body <- dashboardBody(
  fluidRow(
    tabsetPanel(
      id = "main_tab",
      selected = "tab_1",
      tabPanel(title = "tab_1", "Tab content 1"),
      tabPanel(title = "tab_2", "Tab content 2")
    )
  )
)

load_tab2 <- function(input, output, session){
  observeEvent(input$main_tab == 'tab_2', {
    insertUI(
      selector = "#menu_sidebar",
      where = "afterEnd",
      ui = conditionalPanel(
        condition = "input.main_tab == 'tab_2'",
        selectizeInput(inputId = "t2", label = "Select by:", choices = c(as.character(40:50))),
        div("Hello Tab 2")
      ),
      immediate = TRUE,
      session = getDefaultReactiveDomain()
    )
  }, ignoreInit = TRUE, once = TRUE)
}

shinyApp(
  ui = dashboardPage(
    dashboardHeader(title = "tabBoxes"),
    sidebar,
    body
  ),
  server = function(input, output, session) {
    callModule(load_tab2, "load_tab2_id")
  }
)

我通过在 server 函数中直接调用 load_tab2 函数解决了这个问题。

library(shiny)
library(shinydashboard)

sidebar <- dashboardSidebar(
  collapsed = FALSE,
  sidebarMenu(
    id = "menu_sidebar",
    conditionalPanel(
      condition = "input.main_tab == 'tab_1'",
      selectizeInput(inputId = "t1", label = "Select by:", choices = c(as.character(30:40))),
      div("Hello Tab 1")
    ))
)

body <- dashboardBody(
  fluidRow(
    tabsetPanel(
      id = "main_tab",
      selected = "tab_1",
      tabPanel(title = "tab_1", "Tab content 1"),
      tabPanel(title = "tab_2", "Tab content 2")
    )
  )
)

load_tab2 <- function(input, output, session){
  observeEvent(input$main_tab == 'tab_2', {
    insertUI(
      selector = "#menu_sidebar",
      where = "afterEnd",
      ui = conditionalPanel(
        condition = "input.main_tab == 'tab_2'",
        selectizeInput(inputId = "t2", label = "Select by:", choices = c(as.character(40:50))),
        div("Hello Tab 2")
      ),
      immediate = TRUE,
      session = getDefaultReactiveDomain()
    )
  }, ignoreInit = TRUE, once = TRUE)
}

shinyApp(
  ui = dashboardPage(
    dashboardHeader(title = "tabBoxes"),
    sidebar,
    body
  ),
  server = function(input, output, session) {
    load_tab2(input, output, session)
  }
)