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

问题描述 投票:1回答:1

我正在尝试实现一项功能,在单击每一行时,我需要获取被单击行的信息,并且相应的行颜色应更改为其他颜色。当我使用Ctrl +鼠标单击选择多行时,相应的行颜色也应更改,并且需要以数组的形式获取相应行的信息。我需要有一个通用的getTrProps函数,该函数应同时实现这两个功能。有人可以帮我吗

代码箱:https://codesandbox.io/s/react-table-row-table-0bbyi

App

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



DataGrid


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


reactjs setstate react-table
1个回答
1
投票

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

您现在可以按住Ctrl键并选择所需的任意行,并且可以在之间切换。如果您不按住该键,则可以选择一个

每次选择行更改的行颜色都可以看到。

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

以及您希望从沙箱中获得的所有这些内容都在打字稿中。

© www.soinside.com 2019 - 2024. All rights reserved.