我在 Shiny 的应用程序中使用模块来显示不同 tabPanels 的内容。我希望能够通过单击一个按钮前往第二个选项卡。我有以下代码:
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 从“两个”变为“两个”(即保持不变),因此不会触发您的 observeEvent。
你可以添加:
observeEvent(input$tabsPanel,{
openTab(input$tabsPanel)
})
因此,当用户手动更改回 tab1(或任何其他选项卡)时,openTab react 值也会更新。
顺便说一下,您不需要模块来做您想做的事,但我假设您有使用它们的特定原因。对于想要实现相同但不需要模块的任何其他人:
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)
关于r - 使用模块时,如何确保 Shiny 的应用程序知道当前打开了哪个选项卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45212937/