首页 > 解决方案 > 材料表不会添加行

问题描述

React 对 JS 来说相当新。尝试将 Material-table 与添加行按钮一起使用。添加行不会添加行。一刷新行被重置。我很确定我在设置/更新状态时做错了。

export default function App() {
  return (
    <div className="App">
      <Tabl
        obj={{
          a: "a",
          items: [{ x: 1 }, { x: 2 }, { x: 3 }]
        }}
      />
    </div>
  );
}

class Tabl extends Component {
  constructor(props) {
    super(props);
    this.state = {
      obj: props.obj
    };
    console.log(JSON.stringify(this.state.obj));
  }

  updateState(newData) {
    this.setState({
      obj: [...this.state.obj.items, newData]
    });
  }

  render() {
    const currObj = this.state.obj;
    const column = [
      {
        title: "a",
        field: "x"
      }
    ];

    const tableIcons = {
      Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
      Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
      Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />)
    };

    return (
      <MaterialTable
        data={currObj.items}
        columns={column}
        icons={tableIcons}
        options={{
          search: false,
          paging: false
        }}
        editable={{
          onRowAdd: (newData) =>
            new Promise((resolve, reject) => {
              setTimeout(() => {
                this.updateState(newData);
                resolve();
              }, 1000);
            })
        }}
      />
    );
  }
}
export default Tabl;

提前致谢。

标签: javascriptreactjsmaterial-uimaterial-table

解决方案


this.updateState 方法未绑定到类。

您可以像这样在构造函数中绑定,

constructor(props) {
    super(props);
    this.state = {
      obj: props.obj
    };
    console.log(JSON.stringify(this.state.obj));
    this.updateState= this.updateState.bind(this);
  }

推荐阅读