如何获取 React Table 行数据 Onclick

How to get React Table Row Data Onclick

您好,我正在尝试设置我的 React 应用程序,以便当您单击我的 React-table 行项目中的按钮时,该行中的数据将传递到另一个组件。目前我只是在尝试 console.log 正确的数据,但不确定如何根据点击传递 react-table 行数据。我怎样才能做到这一点? 谢谢

我的虚拟数据与按钮(显示详细视图)一起存储在状态中,我想触发数据传递 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"
      }
    ]

我调用 table:

<ReactTable columns={this.state.columns} data={this.state.posts}></ReactTable>

我的 onclick 处理程序函数,但我不确定如何访问我之后的 table 行数据

handleShow(e) {
    console.log(e);
  }

您需要为该行添加一个 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>

查看此 post 了解更多信息 react-table component onClick event for a column

还要确保在构造函数中绑定函数,或使用以下语法:

handleShow = (e) => {
    console.log(e);
  }

对于 React-table v7:

将回调属性 onRowClicked 传递给 table 组件,

在您的 table 组件中调用回调:

...row.getRowProps({
         onClick: e => props.onRowClicked && props.onRowClicked(row, e),
})

In react-table v7, all the spread operator on HTML element that starts with get...Props are props getter, for example:

row.getRowProps(), cell.getCellProps(), column.getHeaderProps(), getTableBodyProps(), getTableProps() etc.. You can pass any more attributes to extend it. for example:

    ...cell.getCellProps({ 
        style: {color: 'red'},  
        onClick: ()=> {}   
    }) 

在您的 Table 定义中:

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);
}