[英]How to get the row index of a clicked cell in react-table?
您好,我正在使用 React Table。 这是我的演示沙盒 - https://codesandbox.io/embed/vq60okkz20?codemirror=1
我想获取单击的单元格 div 的行索引。 我有两列,其中的单元格有一个可点击的 div。 我想获取这些单元格的行索引
直接来自 React-table 文档:
// When any Td element is clicked, we'll log out some information
<ReactTable
getTdProps={(state, rowInfo, column, instance) => {
return {
onClick: (e, handleOriginal) => {
console.log("A Td Element was clicked!");
console.log("It was in this row:", rowInfo);
// IMPORTANT! React-Table uses onClick internally to trigger
// events like expanding SubComponents and pivots.
// By default a custom 'onClick' handler will override this functionality.
// If you want to fire the original onClick handler, call the
// 'handleOriginal' function.
if (handleOriginal) {
handleOriginal();
}
}
};
}}
/>
rowInfo
对象将具有以下形状:
row: Object, // the materialized row of data
original: , // the original row of data
index: '', // the index of the row in the original array
viewIndex: '', // the index of the row relative to the current view
level: '', // the nesting level of this row
nestingPath: '', // the nesting path of this row
aggregated: '', // true if this row's values were aggregated
groupedByPivot: '', // true if this row was produced by a pivot
subRows: '', // any sub rows defined by the `subRowKey` prop
通过访问rowInfo.index
,您将获得单元格的行索引。
工作示例: https ://codesandbox.io/s/nr8w9q6z2m
我会建议使用 onClick 处理程序来获取价值。 您可以添加一个唯一的 ID 以获取确切的元素。
这是一个非常简单的示例
<div onClick={this.onClickHandler}></div>
onClickHandler = (event) =>{
Let id =event.target.id
...
//perform operations
}
id 可以随机生成
如果您正在进行功能渲染,这可能会有所帮助
<tbody {...getTableBodyProps()}>
rows.slice(0, 10).map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell, i) => {
return (
<td {...row.getRowProps({onClick: (e)=>handleTableCellClick(e,row)})}>{cell.render("Cell")}</td>
);
})}
</tr>
);
})
</tbody>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.