【问题标题】:How can I set the parent component state based on children component checkbox value?如何根据子组件复选框值设置父组件状态?
【发布时间】:2021-02-22 15:04:14
【问题描述】:

我正在使用 Material UI Table 组件。
在 Table 组件中,我想将 EnhancedTableHead 中的选中属性存储到我的父组件 EventManagement。

但我不确定正确的方法是什么,因为我需要从中提取事件对象,以获取选中的道具

App.js

export default class EventManagement extends Component {
  state = {
    // How to set the below state by refering the table checkbox
    isSelectAllCheckboxSelected: false
  };

  render() {
    return <Table />;
  }
}

Demo.js(表格组件)

function EnhancedTableHead(props) {
...
  return (
    <TableHead>
      <TableRow>
        <TableCell padding="checkbox">
          {/* How to get the checked prop below and send it to parent component */}
          <Checkbox
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
            inputProps={{ "aria-label": "select all desserts" }}
          />
        </TableCell>
      </TableRow>
    </TableHead>

在这种情况下,由于选中了全选复选框,因此状态 isSelectAllCheckboxSelected 应该为 true。

代码沙盒:
https://codesandbox.io/s/material-demo-forked-hf5z9?file=/demo.js

【问题讨论】:

  • 您可以传递一个回调,当您在子组件中执行操作时,该回调将更新父组件的状态。

标签: javascript reactjs


【解决方案1】:

在您的 App.js 中为您的 Table 函数提供 props 函数:

return <Table checkAllButtonTrue={(value)=> {this.setState({isSelectAllCheckboxSelected: value})}}/>;

然后从表函数中获取道具:

export default function EnhancedTable(props) {
 ...

在你的handleSelectAllClick函数中调用props函数:

const handleSelectAllClick = (event) => {
if (event.target.checked) {
  const newSelecteds = rows.map((n) => n.name);
  props.checkAllButtonTrue(true);
  setSelected(newSelecteds);
  return;
} else {
  props.checkAllButtonTrue(false);
}
setSelected([]);
};

sandbox

【讨论】:

    【解决方案2】:

    您可以在 EventManagement 中创建一个回调,它会在每次复选框单击时做出反应,并检查选定复选框的数量是否等于复选框的数量。然后你可以根据结果设置isSelectAllCheckboxSelected。

    在您的情况下,您可以在 handleClick 中执行此操作:newSelected.length 是选中复选框的数量,您可以将其与 rows.length 进行比较并使用回调发送结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-14
      • 2021-06-29
      • 2013-12-16
      • 2020-12-14
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2016-07-19
      相关资源
      最近更新 更多