嗨,我正在尝试设置我的react应用程序,以便当您在我的react-table中单击一个行中的一个按钮时,该行中的数据将传递到另一个组件。目前,我只是在尝试安装。我怎样才能做到这一点?谢谢
我的虚拟数据与按钮一起存储在状态中(显示详细视图(,我想触发传递的数据:
: columns: [
{
Header: "First Name",
accessor: "fname"
},
{
Header: "Last Name",
accessor: "lname"
},
{
Header: "Employee Group",
accessor: "egroup"
},
{
Header: "Date of Birth",
accessor: "dob"
},
{
Header: "",
id: "id",
Cell: ({ row }) => (
<button onClick={e => this.handleShow()}>
Detailed View
</button>
)
},
],
posts: [
{
fname: "gerald",
lname: "nakhle",
egroup: "faisbuk",
dob: "8/10/1995"
}
]
我渲染桌子的呼吁:
<ReactTable columns={this.state.columns} data={this.state.posts}></ReactTable>
我的onclick处理程序功能,但我不确定如何访问我之后的表行数据
handleShow(e) {
console.log(e);
}
在您的表定义中:
export function TableCustom({handleShow}) {
const columns = React.useMemo(() => [{
Header: 'Action',
accessor: 'action',
Cell: props => <button className="btn1" onClick={() => handleShow(props)}>Details</button>,
},]
return <ReactTable>;
});
和您的父组件中:查看单击行的数据:
const handleShow = (cell) => {
console.log(cell?.row?.original);
}
您需要为行添加一个onclick处理程序
const onRowClick = (state, rowInfo, column, instance) => {
return {
onClick: e => {
console.log('A Td Element was clicked!')
console.log('it produced this event:', e)
console.log('It was in this column:', column)
console.log('It was in this row:', rowInfo)
console.log('It was in this table instance:', instance)
}
}
}
<ReactTable columns={this.state.columns} data={this.state.posts} getTrProps={onRowClick}></ReactTable>
查看此帖子以获取更多信息反应表组件OnClick事件
for React-Table V7:
将回调prop onRowClicked
传递到表组件,
在您的表组件中调用回调:
...row.getRowProps({
onClick: e => props.onRowClicked && props.onRowClicked(row, e),
})
在反应表V7中,启动的HTML元素上的所有传播算子使用
get...Props
是Props Getter,例如:row.getrowprops((,cell.getCellProps((,column.getheaderprops((,getTableBodyProps((,getTableProps((等。您可以通过扩展它的属性。例如:
...cell.getCellProps({
style: {color: 'red'},
onClick: ()=> {}
})
在 @tanstack/react-table v8上,您可以简单地放在表组件上:
// this is your table component
<table>
{table.getRowModel().rows.map((row) => {
// onRowClick is a custom table prop -> onRowClick: (row: Row<any>) => void
return <tr onClick={onRowClick(row)}> ... </tr>
})}
</table>
,然后在您的组件声明上:
<ReactTable data={data} columns={columns} onRowClick={(row) => console.log(row.original)} />
,如果您不想添加另一列以放置可点击按钮,而只是使行可单击。
尝试这个。
onClick={(e) => {console.log(row)}}
还确保您在构造函数中绑定函数,或使用以下语法:
handleShow = (e) => {
console.log(e);
}