我有一个像这样设置的 React 组件:
export default class FormDialog extends React.Component {
constructor(){
super();
this.state = {allowedToDelete: false};
}
onChange(event) {
if (event.target.value.match(this.targetName)) {
console.log("It's a match!");
this.state = {allowedToDelete: true};
console.log(this.state);
} else {
this.state = {allowedToDelete: false};
}
}
render() {
const { profile, deleteUser, handleDialogClose, ...other } = this.props;
this.targetName = `${profile.firstName} ${profile.lastName}`;
console.log({...other})
return (
<Dialog {...other}>
<DialogTitle id="form-dialog-title">Delete this user?</DialogTitle>
<DialogContent>
<DialogContentText>
allowedToDelete: {String(this.state.allowedToDelete)}
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="User's Full Name"
type="text"
fullWidth
onChange={this.onChange.bind(this)}
/>
</DialogContent>
<DialogActions>
<Button variant="outlined" onClick={this.handleDialogClose} color="primary">
Cancel
</Button>
<Button variant="outlined" onClick={this.deleteUser} disabled={!this.state.allowedToDelete} color="primary">
Delete User!
</Button>
</DialogActions>
</Dialog>
);
}
}
(我在这里使用 material-ui 的表单对话框组件)。
如上,提示用户键入他们要删除的配置文件的全名;如果它们匹配名称,则“删除用户!” 按钮应变为未禁用状态。
我的onChange()
事件是工作,因为当我键入正确的名字,我看到It's a match!
在我的控制台和日志this.state
显示,this.state.allowedToDelete === true
。
但是,我的渲染功能allowedToDelete: {String(this.state.allowedToDelete)}
和我的按钮disabled={!this.state.allowedToDelete}
都保持false
.
我在这里做错了什么?我是 React 的新手,我对状态的理解可能会感到困惑,但是我尝试使用直接附加到this
状态而不是状态的变量来执行此操作,但这也不起作用......
你需要打电话setState
。你可以在 react docs 中阅读它。这就是告诉 React 组件触发生命周期以显示新状态的原因。
this.setState({allowedToDelete: false});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句