How to get React Table Row Data Onclick

回眸只為那壹抹淺笑 提交于 2020-06-16 08:41:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!