使用 moduleServer() 基于 tabPanel 值的 conditionalPanel

conditionalPanel based on values of tabPanel using moduleServer()

我正在尝试在开发 shinyApp 时使用模块,但我未能添加在主面板中更改 tabPanel 时更改的侧边栏面板。例如,当用户使用“Tab1”时,应将 h4() 元素添加到带有“Title”的侧边栏面板,而当用户使用“Tab2”时,侧边栏面板应显示 selectInput()。这是我正在使用的代码。知道我做错了什么吗?

library(shiny)
# Module UI ####
modUI = function(id) {
  ns = NS(id)
  tabPanel("Dummy Panel",
           sidebarPanel("SibeBarPanel",
                        conditionalPanel("input.ns(mainpanel) == 1", 
                                         h4("Title")),
                        conditionalPanel("input.ns(mainpanel) == 2",
                                         selectInput(ns("s_1"), "Label1", choices = c("A","B")))
           ),
           
           mainPanel(
             tabsetPanel(id=ns("mainpanel"),
                         tabPanel("Tab1", value = 1),
                         tabPanel("Tab2", value = 2))))
}

# Module Server ####
modServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
  })
}

server = function(input, output, session) {
  modServer("v1")
}


ui = shinyUI(
  navbarPage("Dummy", 
             navbarMenu("This", 
                        modUI("v1")))
)

server = function(input, output, session) {
  modServer("v1")
}

shinyApp(ui, server)

现在 conditionalPanel 有一个 ns 参数:

The namespace() object of the current module, if any.

请检查以下内容:

library(shiny)
# Module UI ####
modUI = function(id) {
  ns = NS(id)
  tabPanel("Dummy Panel",
           sidebarPanel("SibeBarPanel",
                        conditionalPanel("input.mainpanel == 1", 
                                         h4("Title"), ns = ns),
                        conditionalPanel("input.mainpanel == 2",
                                         selectInput(ns("s_1"), "Label1", choices = c("A","B")), ns = ns)
           ),
           
           mainPanel(
             tabsetPanel(id=ns("mainpanel"),
                         tabPanel("Tab1", value = 1),
                         tabPanel("Tab2", value = 2))))
}

# Module Server ####
modServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    
  })
}

server = function(input, output, session) {
  modServer("v1")
}


ui = shinyUI(
  navbarPage("Dummy", 
             navbarMenu("This", 
                        modUI("v1")))
)

server = function(input, output, session) {
  modServer("v1")
}

shinyApp(ui, server)

结果:

    <div data-display-if="input.mainpanel == 1" data-ns-prefix="v1-">
      <h4>Title</h4>
    </div>