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

点击reactable行时同时实现选中与展开功能

解决reactable行点击同时实现选中与展开的问题

要实现点击行时同时触发选中和展开详情的效果,你可以在onClick的JS函数中调用reactable表格实例的内置方法,具体实现如下:

修改后的完整代码

library(shiny)
library(reactable)

ui <- fluidPage(
  reactableOutput("table")
)

server <- function(input, output) {
  output$table <- renderReactable({
    reactable(iris[1:5, ],
      details = function(index) {
        htmltools::div(
          "Details for row: ", index,
          htmltools::tags$pre(paste(capture.output(iris[index, ]), collapse = "\n"))
        )
      },
      selection = "single",
      onClick = JS("function(rowInfo) {
        // 获取表格实例与当前行ID
        const table = rowInfo.table;
        const rowId = rowInfo.id;
        
        // 执行选中操作
        table.selectRow(rowId);
        // 执行详情展开/折叠切换
        table.toggleRowDetails(rowId);
      }")
    )
  })
  
}

shinyApp(ui, server)

可选优化:强制展开而非切换

如果希望点击已展开的行时,仅更新选中状态而不折叠详情,可以添加状态判断逻辑:

function(rowInfo) {
  const table = rowInfo.table;
  const rowId = rowInfo.id;
  
  table.selectRow(rowId);
  
  // 仅当行未展开时执行展开操作
  if (!table.getRowDetailsState(rowId)) {
    table.toggleRowDetails(rowId);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:32:39