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

React Table点击行内按钮如何获取对应行属性?

React Table按钮点击获取对应行属性的解决方法

你遇到的问题根源在于按钮的onClick绑定方式错误:当前代码里onClick={toeSearchButtonEvent(props)}是直接调用函数,导致组件渲染时所有行的toeSearchButtonEvent都会执行一遍,而点击按钮时反而没有触发事件——因为onClick需要接收的是一个函数引用,不是函数执行后的结果。

下面提供两种简单的修复方案:

方案一:用箭头函数包裹事件调用

修改列定义中Confirm列的Cell部分,用箭头函数包裹事件函数,确保只有点击时才执行:

{
  Header: 'Confirm',
  id: 'confirm',
  width: 130,
  Cell: (props) => <button type="button" onClick={() => toeSearchButtonEvent(props)}>
    Confirm Match
  </button>
}

对应的事件函数可以直接获取当前行的属性,比如通过props.row.values拿到整行数据:

function toeSearchButtonEvent(props) {
  console.log(props.row.values); // 打印对应行的所有属性
}

方案二:让事件函数返回一个点击回调函数

调整toeSearchButtonEvent,让它返回一个函数,这样绑定到onClick的是返回的函数,只有点击时才会执行内部逻辑:

function toeSearchButtonEvent(props) {
  return () => {
    console.log(props.row.values); // 点击时打印对应行属性
  }
}

此时列定义中的Cell部分可以保持原来的写法:

{
  Header: 'Confirm',
  id: 'confirm',
  width: 130,
  Cell: (props) => <button type="button" onClick={toeSearchButtonEvent(props)}>
    Confirm Match
  </button>
}

优化建议

如果只需要行数据,可以在Cell中直接解构row参数,让代码更简洁:

{
  Header: 'Confirm',
  id: 'confirm',
  width: 130,
  Cell: ({ row }) => <button type="button" onClick={() => toeSearchButtonEvent(row.values)}>
    Confirm Match
  </button>
}

对应的事件函数可以直接接收行数据:

function toeSearchButtonEvent(rowData) {
  console.log(rowData); // 直接拿到对应行的属性
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:24:18