我正在尝试将 react-table 用作复选框表。The first column will be the checkboxes, when a checkbox gets selected i want to save the id that was defined in the accessor in the state.
我一直在看这些例子,并通过官方文档,到目前为止没有太多运气。
到目前为止我的代码:
import React from 'react';
import ReactTable from "react-table";
import 'react-table/react-table.css'
export default class TableAccessor extends React.Component {
constructor(props){
super(props);
this.state = { personId: null }
//Data to show inside the table, when an item gets selected the ID has to be set in the state
this.data= [
{id: 1, first_name: 'Emma', last_name: 'Smith', email: 'emma@example.com'},
{id: 2, first_name: 'Liam', last_name: 'Miller', email: 'liam@example.com'}
];
//Header data for the table
this.columns = [
{Header: '#', accessor: 'id', Cell: () => <input onChange={() => {
//Here i want to get the ID of the selected item defined in this.data
this.setState({personId: this.data.id});
}} type="checkbox"></input>},
{Header: 'First name', accessor: 'first_name'},
{Header: 'Last name', accessor: 'last_name'},
{Header: 'Email', accessor: 'email'}
];
}
logger = () => {
console.log("personId: " + this.state.personId)
}
render() {
return(
<div className="wrapper">
<button onClick={this.logger}>Print</button>
<ReactTable data={this.data} columns={this.columns} />
</div>
);
}
}
我还希望当时只能选中一个复选框。我看到人们用单选按钮解决了这个问题,但是当我更改为时,type="checkbox"
我type="radio"
仍然可以选择多个项目。
谁能帮助我克服这个问题并解释我在状态中保存访问器值的最佳方法是什么?
提前致谢 :)