反应setstate不触发关闭MUI对话框

时间:2019-03-18 10:19:26

标签: javascript reactjs dialog material-ui

与提供的演示不同,我在Material UI中使用的对话框已设置在其自己的组件中-https://material-ui.com/demos/dialogs/

我可以打开对话框,并且状态从false变为true。我为关闭添加了handleClose,应该将状态设置为false ...,但再次返回true。有人可以指出我在这里做错了什么吗?

https://codesandbox.io/s/zlmj2k3pom

this.state = {
  open: false
};

state = {
  open: false
};

handleClose = () => {
  this.setState({ open: false });
};

2 个答案:

答案 0 :(得分:1)

您正在渲染中使用props中的open变量,因此更改state.open无效。

  render() {
    const { open, id } = this.props;

我建议您做以下事情:

  1. 在构造函数中设置state = { open: this.props.open }
  2. 然后在渲染函数中使用state.open变量

答案 1 :(得分:1)

您可以使用为其提供的openVehicleDialog道具来关闭模态,而不是在open组件中复制onClose状态。

示例

class VehicleDialog extends Component {
  render() {
    const { open, id, onClose } = this.props;

    return (
      <React.Fragment>
        <Dialog aria-labelledby="customized-dialog-title" open={open}>
          <DialogTitle id="customized-dialog-title">Modal title</DialogTitle>
          <DialogContent>
            <Typography gutterBottom>
              Cras mattis consectetur purus sit amet fermentum. Cras justo odio,
              dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta
              ac consectetur ac, vestibulum at eros.
            </Typography>
            <Typography gutterBottom>
              Praesent commodo cursus magna, vel scelerisque nisl consectetur
              et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor
              auctor.
            </Typography>
            <Typography gutterBottom>
              Aenean lacinia bibendum nulla sed consectetur. Praesent commodo
              cursus magna, vel scelerisque nisl consectetur et. Donec sed odio
              dui. Donec ullamcorper nulla non metus auctor fringilla.
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button color="primary" onClick={() => onClose(id)}>
              Close
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    );
  }
}