简体   繁体   English

如何传递道具以仅显示表格中的某些列?

[英]How could I pass in props to display only certain columns in my table?

I'm using data in JSON format to be displayed in a table. 我正在使用JSON格式的数据显示在表中。 What is the best approach passing in a prop to only display(or not display) a certain group of columns in a table? 传递道具以仅显示(或不显示)表中的某些列的最佳方法是什么?

 componentDidMount() {

   fetch('http://localhost:7000/worldStats')
  .then((data) => data.json())
  .then((data) => this.setState( { stats: data } ));
 }

 render(){
 return(

 // Table..
 {this.state.stats.map( (item) => {
 // Items..
   <td>{item.ID}</td>
   <td>{item.CURRENCY}</td>
   <td>{item.NAME}</td>
   <td>{item.GDP}</td>
   <td>{item.POP}</td>
 })}
 )

Considering that you're rendering a table and all you want to do is toggle which columns to display, I think it makes sense to keep all the logic in a single component. 考虑到您正在呈现一个表,并且您要做的就是切换要显示的列,我认为将所有逻辑保留在一个组件中是很有意义的。 This means there is no need to pass props from one component to then next. 这意味着无需将道具从一个组件传递到下一个组件。 Instead, we'll just be utilizing the component state. 相反,我们将仅利用组件状态。

Consider the following code: 考虑以下代码:

import React from "react";

class Table extends React.Component {
  state = {
    stats: [],
    indexOfFirstExtendedField: 2,
    displayExtendedFields: true
  };

  componentDidMount() {
    const newData = [
      {
        id: 1,
        currency: "USD",
        name: "dollars",
        gdp: "alot",
        pop: "alot"
      },
      {
        id: 2,
        currency: "MEX",
        name: "pesos",
        gdp: "alot",
        pop: "alot"
      }
    ];
    this.setState({
      stats: newData
    });
  }

  toggleDisplay = () => {
    this.setState(prevState => {
      return {
        displayExtendedFields: !prevState.displayExtendedFields
      };
    });
  };

  createTableHeaders = () => {
    const {
      indexOfFirstExtendedField,
      stats,
      displayExtendedFields
    } = this.state;

    if (displayExtendedFields) {
      return Object.keys(stats[0]).map(key => {
        return <th>{key}</th>;
      });
    } else {
      return Object.keys(stats[0])
        .filter((key, index, array) => {
          return array.indexOf(key) < indexOfFirstExtendedField;
        })
        .map(key => {
          return <th>{key}</th>;
        });
    }
  };

  createTableContent = () => {
    const {
      indexOfFirstExtendedField,
      stats,
      displayExtendedFields
    } = this.state;

    if (displayExtendedFields) {
      return stats.map(item => {
        return (
          <tr>
            {Object.values(item).map(value => {
              return <td>{value}</td>;
            })}
          </tr>
        );
      });
    } else {
      return stats.map(item => {
        return (
          <tr>
            {Object.values(item)
              .slice(0, indexOfFirstExtendedField)
              .map(value => {
                return <td>{value}</td>;
              })}
          </tr>
        );
      });
    }
  };

  render() {
    const { stats, displayExtendedFields } = this.state;
    return (
      <div>
        <button onClick={this.toggleDisplay}>
          {displayExtendedFields ? "Collapse" : "Expand"}
        </button>
        <table>
          {stats.length > 0 && this.createTableHeaders()}
          {stats.length > 0 && this.createTableContent()}
        </table>
      </div>
    );
  }
}

export default Table;

The main takeaways here is that we are using two additional state-values to help us determine which fields to display, indexOfFirstExtendedField and displayExtendedFields . 这里主要的外卖是,我们使用了两个额外的状态值,以帮助我们确定要显示的字段, indexOfFirstExtendedFielddisplayExtendedFields This helps us expand and collapse the columns. 这有助于我们扩展和折叠列。

Here's the codesandbox too so you can see it in action: https://codesandbox.io/s/v3062w69v0 这也是codeandbox,因此您可以在操作中看到它: https ://codesandbox.io/s/v3062w69v0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM