Shiny/Reactable/JavaScript是否冲突?Reactable点击事件无响应求助
问题排查与解决方案
问题根源
你使用了Reactable的行级onClick回调,但点击按钮时,Reactable无法正确识别点击事件所属的列ID(column.id会返回undefined),导致回调逻辑直接跳过,未执行alert和模态框触发代码。
修复方案
将行级的onClick替换为单元格级的onCellClick回调,它能精准捕获点击的单元格所属列信息,确保逻辑正常执行。
修改后的完整代码
library(shiny) library(reactable) library(logger) ui <- fluidPage( reactableOutput("reactableTest") ) server <- function(input, output) { logger::log_shiny_input_changes(input) output$reactableTest <- renderReactable({ data <- cbind( MASS::Cars93[1:5, c("Manufacturer", "Model", "Type", "Price")], details = NA ) reactable( data, columns = list( details = colDef( name = "", sortable = FALSE, cell = function() htmltools::tags$button("Show details") ) ), # 替换onClick为onCellClick,并调整参数为colInfo onCellClick = JS("function(rowInfo, colInfo, event) { // Only handle click events on the 'details' column if (colInfo.id !== 'details') { return } // Display an alert dialog with details for the row window.alert('Details for row ' + rowInfo.index + ':\\n' + JSON.stringify(rowInfo.values, null, 2)) // Send the click event to Shiny, which will be available in input$show_details // Note that the row index starts at 0 in JavaScript, so we add 1 if (window.Shiny) { Shiny.setInputValue('show_details', { index: rowInfo.index + 1 }, { priority: 'event' }) } }") ) }) observeEvent(input$show_details,{ showModal( ui = modalDialog( title = "hey, it worked!", input$show_details$index ) ) }) } shinyApp(ui, server)
额外说明
- 确保你的
reactable包是最新版本(当前最新为0.4.4),旧版本可能存在事件绑定的兼容性问题。 - 若坚持使用行级
onClick,可给按钮添加style = "pointer-events: none;",让按钮不捕获点击事件,使行点击事件正常触发,但这种方式会让按钮失去可点击的视觉反馈,不推荐。
内容的提问来源于stack exchange,提问作者heladave
相关产品推荐
相关产品推荐

