Ant Design for React : Show/Hide particular column

淺唱寂寞╮ 提交于 2021-01-29 20:53:48

问题


I need a bit of help here, In an Ant Design table, I need to hide/show a particular column of a table depending on a state value. In the given sandbox link, I need to hide the surname column whenever the switch is Off and show when the switch is On.

Please, someone, look into this, and help me out.

Reference: https://codesandbox.io/s/purple-sun-1rtz1?file=/index.js


回答1:


There is a working code, but it should be more customize, interactivize, and refactorize depending on your need:

// You can also modify the data in the `handleChnage`
// Or conditionally display it like here:

class EditableTable extends React.Component {
  state = {
    surNameShow: false
  };
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: "Name",
        dataIndex: "name",
        width: "30%"
      },
      {
        title: "Surname",
        dataIndex: "surname",
        width: "30%"
      }
    ];
    this.state = {
      dataSource: [
        {
          key: "0",
          name: "Edward 1",
          surname: "King 1"
        },
        {
          key: "1",
          name: "Edward 2",
          surname: "King 2"
        }
      ]
    };
  }
  handleChnage = key => {
    this.setState({ surNameShow: !this.state.surNameShow }, () => {
      console.log(this.state.surNameShow);
    });
  };

  render() {
    const { dataSource } = this.state;
    const columns = this.columns;
    return (
      <div>
        <p className="mr-3"> Show surname</p>
        <Switch onChange={() => this.handleChnage()} />
        <Table
          bordered
          dataSource={dataSource}
          columns={
            this.state.surNameShow
              ? columns
              : columns.filter(ea => ea.dataIndex !== "surname")
          }
          pagination={false}
        />
      </div>
    );
  }
}

ReactDOM.render(<EditableTable />, document.getElementById("container"));


来源:https://stackoverflow.com/questions/62751933/ant-design-for-react-show-hide-particular-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!