react-table 上的行级操作:React Js

Row level operations on react-table: React Js

我正在尝试实现一项功能,在点击每一行时,我需要获取被点击行的信息,并且相应的行颜色应该更改为其他颜色。而当我 select 多行使用 Ctrl+鼠标单击 相应的行颜色也应该改变,并且需要以数组的形式获取相应行的信息。我需要一个通用的 getTrProps 函数来实现这两个 .谁能帮我解决这个问题

Codesandbox:https://codesandbox.io/s/react-table-row-table-0bbyi

应用程序

import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";
import { Column } from "react-table";

interface IProps {}

interface IState {
  data: IUser[];
  columns: Column<IUser>[];
}
export interface IUser {
  firstName: string;
  status: "Submitted" | "Pending" | "Approved";
  age: string;
}
export interface IColum {
  Header: string;
  accessor: string;
}
class App extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      data: [],
      columns: []
    };
  }

  componentDidMount() {
    this.getData();
    this.getColumns();
  }

  getData = () => {
    const data: IUser[] = [
      { firstName: "Jack", status: "Submitted", age: "14" },
      { firstName: "Simon", status: "Pending", age: "15" },
      { firstName: "Pete", status: "Approved", age: "17" }
    ];
    this.setState({ data });
  };

  getColumns = () => {
    const columns: IColum[] = [
      {
        Header: "First Name",
        accessor: "firstName"
      },
      {
        Header: "Status",
        accessor: "status"
      },
      {
        Header: "Age",
        accessor: "age"
      }
    ];
    this.setState({ columns });
  };

  onClickRow = (rowInfo: IUser) => {
    console.log("You clicked: " + JSON.stringify(rowInfo));
  };

  render() {
    return (
      <>
        <DataGrid
          data={this.state.data}
          columns={this.state.columns}
          rowClicked={this.onClickRow}
        />
        <DataGrid data={this.state.data} columns={this.state.columns} />
      </>
    );
  }
}



数据网格


import * as React from "react";
import ReactTable, {
  RowInfo,
  Column,
  ComponentPropsGetterR
} from "react-table";
import "react-table/react-table.css";
import { IUser, IColum } from ".";

interface IProps {
  data: IUser[];
  columns: Column<IUser>[];
  // The ? makes it optional
  rowClicked?: (user: IUser) => void;
}

export default class DataGrid extends React.Component<IProps> {
  rowClick: ComponentPropsGetterR = (state: any, rowInfo: RowInfo) => {
    const rowClicked = this.props.rowClicked;
    return rowClicked
      ? {
          onClick: () => rowClicked(rowInfo.original as IUser)
        }
      : {};
  };
  render() {
    return (
      <ReactTable
        data={this.props.data}
        columns={this.props.columns}
        getTrProps={this.rowClick}
      />
    );
  }
}


这是您的最终答案: https://codesandbox.io/s/react-table-row-table-3xwxi

您现在可以按住 Ctrl 键和 Select 任意多行,并且可以在两者之间切换。 如果你没有钥匙,你可以select一个

可以看到每次选择一行颜色的变化。

并且您拥有 this.state.allData 中的所有数据。

所有这些都可以在你的沙箱中使用打字稿。