与提供的演示不同,我在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 });
};
答案 0 :(得分:1)
您正在渲染中使用props中的open
变量,因此更改state.open
无效。
render() {
const { open, id } = this.props;
我建议您做以下事情:
state = { open: this.props.open }
state.open
变量答案 1 :(得分:1)
您可以使用为其提供的open
和VehicleDialog
道具来关闭模态,而不是在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>
);
}
}