我正在将react-table用于数据网格。我已经将react-table提取为一个单独的组件,在其中,我只是将必要的道具传递给它,并渲染了网格。

每当我单击它时,我都试图获取与特定行相关的信息。我正在尝试getTrProps,但似乎无法正常工作。

沙箱:https://codesandbox.io/s/react-table-row-table-g3kd5

应用组件

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



DataGrid组件

import * as React from "react";
import ReactTable from "react-table";
import "react-table/react-table.css";

interface IProps {
  data: any;
  columns: any;
  rowClicked(): void;
}

interface IState {}

export default class DataGrid extends React.Component<IProps, IState> {
  onRowClick = (state: any, rowInfo: any, column: any, instance: any) => {
    this.props.rowClicked();
  };

  render() {
    return (
      <>
        <ReactTable
          data={this.props.data}
          columns={this.props.columns}
          getTdProps={this.onRowClick}
        />
      </>
    );
  }
}

最佳答案

使用以下代码获取单击的行的信息:

 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

关于javascript - 单击某行后,获取该特定行的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57710199/

10-09 18:24
查看更多