子组件中的函数无法在父组件中设置状态

时间:2018-10-01 23:43:59

标签: javascript reactjs material-ui

我正在对项目进行反应。这是我的父组件代码:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deleteConfirm: false
    };
  }

  onDelete = pass => {
    this.setState({ deleteConfirm: false });
    if (pass === true) {
      const { menu, onDelete, restaurantId } = this.props;
      //onDelete(menu.id, restaurantId);
    }
  };

  openDiag() {
    this.setState({ deleteConfirm: true });
  }

  render() {
    return (
      <div>
        <Button
          className={classes.button}
          variant="contained"
          color="secondary"
          onClick={this.openDiag.bind(this)}
        >
          Delete
          {this.state.deleteConfirm ? (
            <Child onDelete={this.onDelete.bind(this)} />
          ) : null}
          <Delete className={classes.rightIcon} />
        </Button>
      </div>
    );
  }
}

父组件的状态称为deleteConfirm,如果我按Delete键,则deleteConfirm设置为true,并且呈现子组件。函数OnDelete传递给子组件, 子组件是Material Ui对话框,用于确认删除操作。这是代码:

class Child extends Component {
  state = {
    open: true
  };

  handleClose = (e, confirm) => {
    const { onDelete } = this.props;
    if (confirm === true) {
      onDelete(true);
    } else {
      onDelete(false);
    }
    this.setState({ open: false });
  };

  render() {
    return (
      <div>
        <Dialog
          open={this.state.open}
          onClose={e => this.handleClose(e, false)}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
        >
          <DialogActions>
            <Button onClick={e => this.handleClose(e, false)} 
              color="primary">
              Cancel
            </Button>
            <Button
              onClick={e => this.handleClose(e, true)}
              color="primary"
              autoFocus
            >
              Confirm
            </Button>
          </DialogActions>
        </Dialog>
      </div>
    );
  }
}

如果按下取消按钮,则删除操作将被取消,并调用父函数onDelete。父组件中的deleteConfirm应该设置为false。但是,状态始终为真,我无法更改。非常感谢任何想帮助我的人。谢谢!

1 个答案:

答案 0 :(得分:1)

经典的Event Propagation错误。您将一个点击处理程序嵌入到另一个点击处理程序中,这会逆转内部点击处理程序的逻辑。

在内部处理程序中使用event.stopPropagation或重新排列元素,使它们不会相互嵌套:

  render() {
    return (
      <div>
        <Button
          className={classes.button}
          variant="contained"
          color="secondary"
          onClick={this.openDiag.bind(this)}
        >
          Delete
          <Delete className={classes.rightIcon} />
        </Button>

        {this.state.deleteConfirm ? (
          <Child onDelete={this.onDelete.bind(this)} />
        ) : null}
      </div>
    );