我正在将react-table用于数据网格。我已将react-table提取为一个单独的组件,在其中,我只是将必要的道具传递给它,并渲染了网格。
每当我单击它时,我都试图获取与该行相关的信息。我正在尝试getTrProps,但似乎无法正常工作。
沙箱:https://codesandbox.io/s/react-table-row-table-g3kd5
npm run server-start && npm run react-start
import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";
interface IProps {}
interface IState {
data: {}[];
columns: {}[];
}
class App extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
data: [],
columns: []
};
}
componentDidMount() {
this.getData();
}
getData = () => {
let data = [
{ firstName: "Jack", status: "Submitted", age: "14" },
{ firstName: "Simon", status: "Pending", age: "15" },
{ firstName: "Pete", status: "Approved", age: "17" }
];
this.setState({ data }, () => this.getColumns());
};
getColumns = () => {
let columns = [
{
Header: "First Name",
accessor: "firstName"
},
{
Header: "Status",
accessor: "status"
},
{
Header: "Age",
accessor: "age"
}
];
this.setState({ columns });
};
onClickRow = () => {
console.log("test");
};
render() {
return (
<>
<DataGrid
data={this.state.data}
columns={this.state.columns}
rowClicked={this.onClickRow}
/>
</>
);
}
}
render(<App />, document.getElementById("root"));
答案 0 :(得分:1)
使用此代码获取点击行的信息:
getTdProps={(state, rowInfo, column, instance) => {
return {
onClick: (e, handleOriginal) => {
console.log("row info:", rowInfo);
if (handleOriginal) {
handleOriginal();
}
}
}}}
您可以查看以下CodeSandbox示例:https://codesandbox.io/s/react-table-row-table-shehb?fontsize=14
答案 1 :(得分:1)
您的代码中有很多错误,但是要将值传递回去,您必须将其放入回调中:
onRowClick = (state: any, rowInfo: any, column: any, instance: any) => {
this.props.rowClicked(rowInfo);
};
并像这样读出来:
onClickRow = (rowInfo) => {
console.log(rowInfo);
};
希望这会有所帮助。