React JS:针对 table 实施 Show/More

React JS: Implementing Show/More with respect to a table

我正在尝试针对 table 实现 show more/show less 功能。 Show More/ Show less link 应该只在有超过 2 个元素时可见并且显示较少应该将其设置回默认的项目数(即在我的情况下为 2)。Show More 应该打印其余的这几项。我正在使用 react-table 因为 same.There 是一个数据网格组件,我在其中传递必要的道具,并尝试在 child.

中实现此逻辑

我尝试了以下方法。谁能告诉我哪里出错了?

沙盒:https://codesandbox.io/s/react-table-row-table-ryiny?file=/src/index.js

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

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }), () => {
      const subset: = this.state.showMore ? this.props.data : this.props.data.slice(0, 2);
    });
  }

  renderTableData = () => {
    const { data } = this.props;
    const subset = this.state.showMore ? data : data.slice(0, 2);
    return subset;
  };

  render() {
    const { showMore  } = this.state;
    const { data,columns } = this.props;
    const showLink = data.length > 2;
    return (
            <>
            {showLink && (
              <a onClick={this.toggleState}>
                Show {showMore ? "Less" : "More")}
              </a>
            )}
          <ReactTable
            showPagination={false}
            data={data}
            columns={columns}
          />
        </>
    )
  }
}


'columns' 处于 props 而不是状态,如果这是您需要的唯一功能,则删除 renderTableData 函数

试试这个

...

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMore: false,
    };
  }

  toggleState = () => {
    this.setState(prevState => ({
      showMore: !prevState.showMore
    }));
  }

  render() {
    const { showMore } = this.state;
    const { data, columns } = this.props;
    const showLink = data.length > 2;
    const subset = showMore ? data : data.slice(0, 2);
    return (
            <>
            {showLink && (
              <a onClick={this.toggleState}>
                Show {showMore ? "Less" : "More"}
              </a>
            )}
          <ReactTable
            showPagination={false}
            data={subset}
            columns={columns}
          />
        </>
    )
  }
}