在react.js中创建动态列

时间:2018-05-27 14:01:40

标签: javascript reactjs react-data-grid

我正在尝试在react.js中创建一个动态列,任何人都有想法?我已经完成了静态列,但我想让它们动态看看我的代码,请给我建议。

import React from 'react';
import ReactDataGrid from 'react-data-grid';
class Example extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.createRows();
    this._columns = [
      { key: 'id', name: 'ID' },
      { key: 'title', name: 'Title' },
      { key: 'count', name: 'Count' } ];

    this.state = null;
  }

  createRows = () => {
    let rows = [];
    for (let i = 1; i < 5; i++) {
      rows.push({
        id: i,
        title: 'Title ' + i,
        count: i * 1000
      });
    }

    this._rows = rows;
  };

  rowGetter = (i) => {
    return this._rows[i];
  };

  render() {
    return  (
      <ReactDataGrid
        columns={this._columns}
        rowGetter={this.rowGetter}
        rowsCount={this._rows.length}
        minHeight={200} />);
  }
}

export default Example;

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此功能来创建动态列键和名称

createColumns = async (data) => {
    let columns = [], keys = [];
    if (data)
        keys = Object.keys(data);
    for (let i = 0; i < keys.length; i++) {
        columns.push({key: Object.keys(data)[i], name: Object.keys(data)[i]});
    }

    await this.setState({columns});
};