You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny模块中Highcharts树状图点击事件失效问题求助

解决Shiny模块中Highcharts Treemap点击失效的问题

问题原因

你猜的没错,就是命名空间的问题。Shiny模块中的所有输入/输出ID都会自动带上模块的命名空间前缀(比如你的模块ID是ex1,输入ID会变成ex1-treemapclick),但你自定义的JS点击事件里直接用了裸IDtreemapclick,没有关联模块的命名空间,导致Shiny无法识别这个输入,点击事件自然无法触发后续响应。

修复方案

在模块的server函数中,通过session$ns()方法生成带命名空间前缀的输入ID,然后把这个ID嵌入到JS点击事件里,确保Shiny能正确绑定模块内的输入。

修改后的模块代码

mod_ex2_UI <- function(id) {
  ns <- NS(id)
  tagList(
    highchartOutput(ns("hcontainer")),
    htmlOutput(ns("clicked"))
  )
}

mod_ex2_Server <- function(id) {
  moduleServer(
    id,
    function(input, output, session) {
      # 关键修改:用session$ns生成带命名空间的输入ID
      click_js <- JS(sprintf(
        "function(event) {Shiny.onInputChange('%s', event.point.name);}",
        session$ns("treemapclick")
      ))

      output$hcontainer <- renderHighchart({
        gapminder::gapminder %>%
          dplyr::filter(year  == 2007) %>%
          highcharter::data_to_hierarchical(group_vars = c(continent, country), size_var = pop) %>%
          hchart(type = "treemap") %>%
          hc_plotOptions(treemap = list(events = list(click = click_js)))
      })

      output$clicked <- renderUI({
        if(is.null(input$treemapclick)){
          reactable::reactable(data =gapminder::gapminder %>%
                                 dplyr::filter(year  == 2007) %>%
                                 dplyr::filter(country == 'China'))
        }else{
          reactable::reactable(data =gapminder::gapminder %>%
                                 dplyr::filter(year  == 2007) %>%
                                 dplyr::filter(country == input$treemapclick))
        }
      })
    }
  )
}

关键修改说明

  • 原来的JS代码直接使用treemapclick作为输入ID,现在通过session$ns("treemapclick")生成带模块命名空间的ID(比如ex1-treemapclick),并通过sprintf嵌入到JS函数中。
  • 这样修改后,点击Treemap节点时,Shiny就能正确识别模块内的input$treemapclick,触发后续的UI更新逻辑。

主程序代码无需修改,保持原样即可。

内容的提问来源于stack exchange,提问作者JohnBones JohnBones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:05:20