如何在Shiny应用中为嵌套tabsetPanel设置独立侧边栏
问题修复方案
你现有代码不生效的核心原因有两个:
- 子选项卡名称大小写不匹配:UI层定义的子选项卡名称是
tab1、tab2,但条件判断中写的是首字母大写的Tab1、Tab2,字符串匹配失败导致条件面板永远不触发 - 缺少父选项卡联动判断:子选项卡的侧边栏控件没有限制仅在父选项卡为
InsiderTraining时显示,切换到其他父选项卡时可能出现控件异常展示的问题
修复后完整可运行代码
library(shiny) library(shinydashboard) library(shinydashboardPlus) shinyApp( ui = tags$body(class="skin-blue sidebar-mini control-sidebar-open",dashboardPage( options = list(sidebarExpandOnHover = TRUE), header = dashboardHeader(title = "Investment Advisor Monitoring - Insider Trading",titleWidth = 450), sidebar = dashboardSidebar(minified = F, collapsed = F, h4("Investment Selected"), uiOutput("mytab11"), uiOutput("mytab12"),uiOutput("mytab13"),uiOutput("mytab14") ), body = dashboardBody( h3('Results'), tabsetPanel(id = "tabs", tabPanel("InsiderTraining", tabsetPanel(id="tabs2", # 统一子选项卡名称为大写,和服务端条件匹配 tabPanel("Tab1"), tabPanel("Tab2"))), tabPanel("Switching"), tabPanel("Tax Loss Harvesting") ) ), controlbar = dashboardControlbar(width = 300, h4("Insider Trading Parameters"), uiOutput("mytab21"), uiOutput("mytab22") ), title = "DashboardPage" )), server = function(input, output) { output$mytab11 <- renderUI({ tagList( conditionalPanel(condition = 'input.tabs=="InsiderTraining"', textInput("StockTicker", "Enter Stock Symbol", value = "NFLX"), sliderInput('periods','Periods',min=1,max=120,value=60), selectInput("mtvar", "Choose a variable", choices = colnames(mtcars)) )) }) output$mytab12 <- renderUI({ tagList( conditionalPanel(condition = 'input.tabs=="Switching"', textInput("StockTicker2", "Enter Stock Symbol", value = "AAPL"), selectInput("cvar", "Choose a variable", choices = colnames(cars)) )) }) output$mytab13 <- renderUI({ tagList( # 增加父选项卡判断,避免切换到其他父选项卡时异常显示 conditionalPanel(condition = 'input.tabs=="InsiderTraining" && input.tabs2=="Tab1"', textInput("StockTicker3", "Enter Stock Symbol", value = "AAPL"), selectInput("cvar2", "Choose a variable", choices = colnames(cars)) )) }) output$mytab14 <- renderUI({ tagList( # 增加父选项卡判断,避免切换到其他父选项卡时异常显示 conditionalPanel(condition = 'input.tabs=="InsiderTraining" && input.tabs2=="Tab2"', textInput("StockTicker4", "Enter Stock Symbol", value = "AAPL"), selectInput("cvar3", "Choose a variable", choices = colnames(cars)) )) }) } )
额外优化点:将原有代码中错误的苹果股票代码
APPL修正为正确的AAPL,避免使用时出现不必要的问题。
内容的提问来源于stack exchange,提问作者firmo23
相关产品推荐
相关产品推荐

