如何在argonDash侧边栏中响应式捕获选中项的tabName
如何响应式捕获argonDash侧边栏选中项的tabName
问题原因
argonDash的侧边栏组件并未像shinydashboard那样内置input$sidebar_menu这类响应式输出,需要手动通过JavaScript监听点击事件,将选中项的tabName传递到Shiny服务器。
解决方案
使用shinyjs监听侧边栏菜单项的点击事件,提取对应项的data-tab属性值(即我们设置的tabName),并将其同步到Shiny的input对象中,实现响应式捕获。同时处理页面初始加载时默认选中项的情况。
修改后的完整代码
library(shiny) library(argonR) library(argonDash) library(shinyjs) # UI argonSidebar <- argonDashSidebar( vertical = TRUE, skin = "light", background = "white", size = "md", side = "left", id = "my_sidebar", icon = tags$img(src = "logo.png", alt = "custom icon"), br(), argonSidebarMenu( id = "sidebar_menu", argonSidebarItem( tabName = "cards", icon = argonIcon(name = "tv-2", color = "info"), "Overview", id = "item_cards" ), argonSidebarItem( tabName = "tables", icon = argonIcon(name = "bullet-list-67", color = "red"), "Charts", id = "item_tables" ), argonSidebarItem( tabName = "bulletin", icon = argonIcon(name = "book-bookmark", color = "green"), "Bulletin", id = "item_bulletin" ) ) ) server <- function(input, output, session) { # 初始化:设置默认选中的tabName(第一个激活项) observe({ runjs(" const initialTab = document.querySelector('.sidebar-item.active a').getAttribute('data-tab'); Shiny.setInputValue('sidebar_selected', initialTab); ") }) # 监听侧边栏项点击事件,实时更新选中的tabName runjs(" document.querySelectorAll('.sidebar-item a').forEach(item => { item.addEventListener('click', function() { const tabName = this.getAttribute('data-tab'); Shiny.setInputValue('sidebar_selected', tabName); }); }); ") # 响应式展示选中的tabName output$selected_tab_display <- renderText({ paste("Selected tab is:", input$sidebar_selected) }) } # Main UI ui <- argonDashPage( useShinyjs(), sidebar = argonSidebar, body = argonDashBody( h2(textOutput("selected_tab_display")) ) ) shinyApp(ui, server)
代码说明
- 初始值设置:页面加载完成后,通过JavaScript定位默认激活的侧边栏项(带有
active类的元素),提取其data-tab属性值并同步到input$sidebar_selected。 - 点击事件监听:为所有侧边栏项的链接标签绑定点击事件,每次点击时读取当前项的
data-tab值,实时更新input$sidebar_selected。 - 响应式展示:通过
renderText读取input$sidebar_selected的值,实现选中tabName的实时展示。
此方案可实现与shinydashboard中input$sidebar_menu完全一致的响应式效果,满足捕获选中侧边栏项tabName的需求。
内容的提问来源于stack exchange,提问作者user3355655
相关产品推荐
相关产品推荐

