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
相关产品推荐
相关产品推荐

