从闪亮模块内部调用updateTabItems模块、updateTabItems

2023-09-03 14:05:55 作者:一句玩笑‘赔上了青春

在我闪亮的应用程序中,我有很多ValueBox,每个ValueBox代表shinydashboard侧边栏中的一个表项。单击ValueBox时,页面应移至正确的选项卡。

我没有多次复制代码,而是编写了一个可重用的模块,该模块呈现valueBox并将valueBox的类更改为actionButton。在服务器部分中,我包含了一个serveEvent,它在单击valueBox时调用updateTabItems。但当点击时,什么也不会发生。该模块似乎无法操作仪表板侧边栏。

library(shiny)
library(shinydashboard)

value_box_output <- function(.id) {
  ns <- NS(.id)
  valueBoxOutput(ns("overview.box"))
}

value_box <- function(input, output, session, .value, .subtitle, .tab.name) {
  ns <- session$ns

  output$overview.box <- renderValueBox({
    box1 <- valueBox(
      .value,
      .subtitle,
      href = "#",
      width = NULL
    )
    box1$children[[1]]$attribs$class <- "action-button"
    box1$children[[1]]$attribs$id <- ns("button")
    box1
  })

  observeEvent(input$button, {
    print("clicked")
    updateTabItems(session, inputId = "tabs", selected = .tab.name)
  })
}


ui <- dashboardPage(
  dashboardHeader(title = "Title"),
  dashboardSidebar(
    sidebarMenu(
    id = "tabs",
    menuItem("Overview", tabName = "Overview"),
    menuItem("Tab 1", tabName = "Tab_1")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem("Overview", value_box_output("tab")),
      tabItem("Tab_1")
    )
  )
)

server <- function(input, output, session) {
  callModule(value_box,
             "tab",
             .value = 33,
             .subtitle = "Tab 1",
             .tab.name = "Tab_1")
}

shinyApp(ui, server)

推荐答案

.Net中堆栈和堆的区别

您可以在此帖子中找到答案:Accessing parent namespace inside a shiny module

基本上,在模具内的updateTabItems()中,您需要调用父模块的会话,而不是模块的会话。

因此,将您的会话的一个变量添加到call Module(),并在updateTabItems()中调用它。