我有检查表单是否正确填写的代码-如果表单填写不正确,则会出现一个对话框弹出窗口,让用户知道其表单填写不正确。我不明白为什么这对我不起作用。
在onSubmit中调用renderError弹出窗口。
state = {
errorOpen: false,
}
toggleErrorModal = () => {
this.setState(prevState => ({ errorOpen: !prevState.errorOpen }));
}
renderError = () => {
return (
<Dialog open={this.state.errorOpen} onClose={this.toggleErrorModal}>
<Grid container >
<DialogTitle > Form Incomplete </DialogTitle>
</Grid>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Please fill out the required fields
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.toggleErrorModal} >
Ok
</Button>
</DialogActions>
</Dialog>
)
}
onSubmit = event => {
event.preventDefault();
let submit = false;
/*Code that checks and sets the submit to true/false*/
if (submit == false) {
this.setState({errorOpen:true}, ()=> {})
this.renderError();
}
};
答案 0 :(得分:1)
在React中,唯一在DOM上呈现元素的函数是render
函数,该函数在创建类的实例或调用setState
时调用。因此,您要做的就是将要呈现的内容放入render
函数中,如下所示:
state = {
errorOpen: false,
};
toggleErrorModal = () => {
this.setState((prevState) => ({ errorOpen: !prevState.errorOpen }));
};
onSubmit = (event) => {
event.preventDefault();
let submit = false;
/*Code that checks and sets the submit to true/false*/
if (submit == false) {
this.setState({ errorOpen: true }, () => {});
}
};
render = () => {
return (
<div>
<Dialog open={this.state.errorOpen} onClose={this.toggleErrorModal}>
<Grid container>
<DialogTitle> Form Incomplete </DialogTitle>
</Grid>
<DialogContent>
<DialogContentText id="alert-dialog-description">Please fill out the required fields</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.toggleErrorModal}>Ok</Button>
</DialogActions>
</Dialog>
<div>Put here the content of your page that is visible when the dialog is closed</div>
</div>
);
};
render
之后无需手动调用setState
函数,因为它是在setState
执行完成后由React自动触发的