【问题标题】:React: Material-ui tableRow can not choose, if using setState in onRowSelectionReact:Material-ui tableRow不能选择,如果在onRowSelection中使用setState
【发布时间】:2017-12-09 16:03:58
【问题描述】:

我有一个材料-ui table 我想传递选定的行以在 DELETE 按钮中起作用。

  constructor(props) {
      super(props);
      this.state = {
            selectedRows: 'none',
      };
      }

  onRowSelection(val){
    console.log(this);
    this.setState({
      selectedRows: val,
    });
  }

render() {
<Table
              fixedHeader={true}
              selectable={true}
              multiSelectable={true}
              onRowSelection={this.onRowSelection.bind(this)}
            >
    ...
               <TableFooter adjustForCheckbox={true}>
                 <TableRow>
                   <TableRowColumn colSpan="5" style={{textAlign: 'right'}}>
                  <RaisedButton
                    primary={true}
                    label="DELETE"
                    labelPosition="after"
                    icon={<ActionDelete/>}
                    onClick={this.props.onDelete.bind(this.state.selectedRows)}
                  />
                   </TableRowColumn>
                 </TableRow>
               </TableFooter>
</Table>
}

我想将 this.state.selectedRows 传递给 this.props.onDelete 函数,但是作为 在此issue 中提到,material-ui 在 onRowSelection 中的 setState 存在问题。

我该如何解决它,是否有另一种方法可以访问选定的行并将它们传递给某个函数以及为什么存在此类错误(如果我在父组件上使用 setState,为什么 onRowSelection 会介意?)

【问题讨论】:

  • 我认为选择消失的原因是 this.setState() 会重新渲染,与 this.forceUpdate() 效果相同。

标签: javascript reactjs material-design state


【解决方案1】:

material-ui 的表格在每次渲染时重置其检查状态存在问题。 要克服这个问题,您需要使用 setTimeout 恢复选中状态并自己管理选中的数组。至少在修复此错误之前。 在该州,有这个:

  state = {
    selectedRows: [],
  };

渲染时,添加:

            <TableRow key={index}
              selected={this.state.selectedRows.indexOf(index) !== -1}>
            </TableRow>

既然您自己保持检查状态,您应该有一个函数来接受检查/取消检查调用,并恢复取消检查所有请求,例如

  onRowSelection(selectedRows) {
    if (selectedRows.length === 0) { // due to a bug in material-ui
      setTimeout(() => { this.setState({ selectedRows: this.state.selectedRows }) }, 100);
      return;
    };
    this.setState({ selectedRows });
  }

      <Table
        onRowSelection={this.onRowSelection}

  constructor(props) {
    super(props);
    this.onRowSelection = this.onRowSelection.bind(this);
  }

您还应该添加一个按钮以允许用户取消选中所有选项。

【讨论】:

    【解决方案2】:

    我认为这里的问题是您使用 bind 函数的方式。 bind 函数的第一个参数应该是thisArg,第二个参数是你想要传递给结果函数的参数。所以你应该像这样将函数传递给onClick

    onClick={this.props.onDelete.bind(this, this.state.selectedRows)}
    

    【讨论】:

    • 不幸的是它没有解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2012-07-06
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多