如何在shinydashboard中为多个DiagrammeR GraphViz图绑定点击切换标签事件
核心问题
你的点击绑定失效有两个原因:
- 所有GraphViz生成的节点id遵循
node1/node2的全局命名规则,多个图共存时id重复,直接按id绑定只会命中页面中第一个出现的对应节点 - 非激活状态的标签页默认是隐藏状态,初始加载时第二个图的DOM节点未挂载,初始的onclick绑定无法捕获到隐藏标签页里的节点
解决方案
用JS事件委托机制绑定点击事件,不需要逐节点绑定,也不受元素动态渲染、标签页隐藏的影响,所有图的节点都能正常触发交互。
完整可运行代码
library(shinydashboard) library(DiagrammeR) library(shinyjs) ui <- dashboardPage( dashboardHeader(title = "DiagrammeR buttons"), dashboardSidebar( sidebarMenu(id = "tabs", menuItem("Tab 1", tabName = "one", icon = icon("dice-one")), menuItem("Tab 2", tabName = "two", icon = icon("dice-two")) ) ), dashboardBody( useShinyjs(), # 新增全局点击事件监听 tags$script(HTML(" $(document).on('click', '.grViz g.node', function() { const nodeId = $(this).attr('id'); let targetTab; // 按你的节点规则映射到对应tabname if (nodeId === 'node1') targetTab = 'one'; if (nodeId === 'node2') targetTab = 'two'; if (targetTab) Shiny.setInputValue('clickednode', targetTab, {priority: 'event'}); }); ")), tabItems( tabItem(tabName = "one", fluidRow(box(grVizOutput("diagram_a", width = "100%", height = "100%"), width = 12)) ), tabItem(tabName = "two", fluidRow(box(grVizOutput("diagram_b", width = "100%", height = "100%"), width = 12)) ) ) ) ) server <- function(input, output, session) { output$diagram_a <- renderGrViz({grViz("digraph { graph[rankdir = LR] node [style = filled] n1_1 -> n1_2 }")}) output$diagram_b <- renderGrViz({grViz("digraph { graph[rankdir = LR] node [style = filled] n2_1 -> n2_2 }")}) observeEvent(input$clickednode, { updateTabItems(session, "tabs", input$clickednode) }) # 已删除原有的逐节点绑定逻辑 } shinyApp(ui, server)
优化建议(可选)
如果你的节点数量多、映射关系复杂,可以在定义digraph时主动给节点设置自定义id,直接和tabname对应,不需要在JS里写判断逻辑:
# 定义grViz时给节点加id属性 grViz("digraph { graph[rankdir = LR] node [style = filled] n1_1 [id = 'one'] n1_2 [id = 'two'] n1_1 -> n1_2 }")
对应的JS可以简化为:
$(document).on('click', '.grViz g.node', function() { const targetTab = $(this).attr('id'); Shiny.setInputValue('clickednode', targetTab, {priority: 'event'}); });
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

