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

模块内DT数据表行操作按钮无法获取ID的技术求助

解决Shiny模块中DT表格按钮无法传递ID的问题

问题根源

Shiny模块会为所有输入/输出ID添加命名空间前缀,但你的代码在两个关键环节未处理命名空间:

  • 表格按钮的ID未添加模块命名空间前缀
  • JavaScript函数将current_id发送到全局会话,而非模块的命名空间上下文

修复方案

以下是修正后的代码:

1. mymodule.R(模块文件)

mymodule_ui <- function(id) {
    ns <- NS(id)
    div(class = "container",
        style = "margin-top: 50px;",
        DT::DTOutput(outputId = ns("dt_table"), width = "100%")
    )
}

mymodule_server <- function(id) {
    moduleServer(id, function(input, output, session) {
        ns <- session$ns
        # 获取带命名空间的current_id输入ID
        current_input_id <- ns("current_id")

        btns <- lapply(1:32, function(x) {
            paste0(
                '&lt;div class = "btn-group"&gt;
                 &lt;button class="btn btn-default action-button btn-info" id="', ns(paste0("edit_", x)), '" type="button" onclick=get_id(this.id, "', current_input_id, '")&gt;&lt;i class="far fa-pen-to-square"&gt;&lt;/i&gt;&lt;/button&gt;
                 &lt;button class="btn btn-default action-button btn-danger" id="', ns(paste0("delete_", x)), '" type="button" onclick=get_id(this.id, "', current_input_id, '")&gt;&lt;i class="fas fa-trash-alt"&gt;&lt;/i&gt;&lt;/button&gt;&lt;/div&gt;'
            )
        }) |> unlist()

        df <- cbind(mtcars, btns)
        colnames(df) <- c(colnames(mtcars), "btns")

        output$dt_table <- DT::renderDT(df, escape = FALSE)

        observeEvent(input$current_id, {
            print(paste("点击的按钮ID:", input$current_id))
        })
    })
}

2. script.js(JavaScript文件)

function get_id(clicked_id, input_id) {
    // 使用带命名空间的输入ID设置值
    Shiny.setInputValue(input_id, clicked_id, {priority: "event"});
}

3. app.R(主应用文件)

无需修改,保持原代码即可:

library(shiny)
library(DT)

source("mymodule.R")

ui <- fluidPage(
    shiny::includeScript("script.js"),
    mymodule_ui("try")
)

server <- function(input, output, session) {
    mymodule_server("try")
}

shinyApp(ui = ui, server = server)

关键改动说明

  • 按钮ID通过ns(paste0("edit_", x))添加了模块命名空间前缀,避免多模块实例的ID冲突
  • 在模块服务器中获取current_id的完整命名空间ID(如try-current_id),并传递给JavaScript函数
  • JavaScript函数直接使用该完整ID设置输入值,确保模块的input$current_id能接收到按钮点击事件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:45:04