问题
Hi I am trying to set up my react app such that when you click on a button in a row item in my react-table the data in that row is passed onto another component. At the moment I am simply trying to console.log the correct data but am unsure of how to pass react-table row data based on click. How can I do this? Thanks
My Dummy data stored in state along with the button (Show Detailed View) which I want to trigger the data passing onclick:
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"
}
]
My Call to render the table:
<ReactTable columns={this.state.columns} data={this.state.posts}></ReactTable>
My onclick handler function but im not sure how I can access the table row data I'm after
handleShow(e) {
console.log(e);
}
回答1:
You will need to add an onClick handler for the row
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>
check this post for more info react-table component onClick event for a column
回答2:
Also make sure you are binding your function in your constructor, or use the following syntax:
handleShow = (e) => {
console.log(e);
}
来源:https://stackoverflow.com/questions/56086420/how-to-get-react-table-row-data-onclick