首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React :对表实现Show/More

React :对表实现Show/More
EN

Stack Overflow用户
提问于 2020-05-28 15:26:41
回答 1查看 1.2K关注 0票数 0

我正在尝试实现与表相关的show more/show less功能。只有当有两个以上的元素时,Show More/ Show less链接才是可见的,而显示较少的元素应该将其设置为默认的项目数(在我的例子中是2)。Show More应该打印其余的项目。我正在使用react表,因为same.There是一个数据网格组件,在这里我传递必要的道具,并试图在子组件中实现这个逻辑。

我试过以下几种方法。有人能告诉我哪里出了问题吗?

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

代码语言:javascript
复制
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}
          />
        </>
    )
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-28 15:58:19

“列”处于道具状态,而不是状态,如果这是您唯一需要的功能,那么删除renderTableData函数

尝尝这个

代码语言:javascript
复制
...

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}
          />
        </>
    )
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62068455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档