如何在Shiny动态UI中获取dataTable的单元格点击事件?
解决Shiny动态生成DT表格无法捕获单元格点击事件的问题
问题根源
你当前代码里,动态表格是用renderUI套着renderDT输出的——这种写法会导致DT表格的实际DOM元素ID不是你定义的dynamic,而是DT内部自动生成的随机ID,所以input$dynamic_cells_selected这个输入对象根本不存在,自然拿不到单元格选择事件。
最简修正方案
别用renderUI中转,直接用renderDT对应DTOutput输出动态表格就行。哪怕需要根据条件动态切换表格内容,也只需要在renderDT里写逻辑判断,不需要额外套renderUI。
修正后的完整代码
library(shiny) library(DT) ui <- fluidPage( textOutput("out"), # 把uiOutput换成DTOutput DTOutput("dynamic"), DTOutput("normal") ) server <- function(input, output, session) { # 去掉renderUI包裹,直接用renderDT输出到dynamic output$dynamic <- renderDT( mtcars, rownames = FALSE, selection = list(mode = "single", target = "cell"), options = list(dom = "t" , pageLength = 5) ) output$normal <- renderDT( iris, rownames = FALSE, selection = list(mode = "single", target = "cell"), options = list(dom = "t" , pageLength = 5) ) output$out <- renderText({ paste( "Normal", paste(input$normal_cells_selected, collapse = " "), "\n", "Dynamic", paste(input$dynamic_cells_selected, collapse = " ") ) }) } shinyApp(ui, server)
特殊场景补充
如果确实需要用uiOutput动态生成(比如要在表格和其他组件之间切换),可以手动给DT指定固定ID:
# UI部分保留uiOutput ui <- fluidPage( textOutput("out"), uiOutput("dynamic"), DTOutput("normal") ) server <- function(input, output, session) { output$dynamic <- renderUI({ # 手动指定DT输出的ID为dynamic_table DTOutput("dynamic_table") }) # 针对指定的ID渲染表格 output$dynamic_table <- renderDT( mtcars, rownames = FALSE, selection = list(mode = "single", target = "cell"), options = list(dom = "t" , pageLength = 5) ) output$normal <- renderDT( iris, rownames = FALSE, selection = list(mode = "single", target = "cell"), options = list(dom = "t" , pageLength = 5) ) # 此时捕获动态表格事件要使用指定ID对应的输入对象 output$out <- renderText({ paste( "Normal", paste(input$normal_cells_selected, collapse = " "), "\n", "Dynamic", paste(input$dynamic_table_cells_selected, collapse = " ") ) }) } shinyApp(ui, server)
这种写法仅适合复杂的动态组件切换场景,一般优先用第一种方案更简洁。
内容的提问来源于stack exchange,提问作者pietrodito
相关产品推荐
相关产品推荐

