Javascript ReactJS:element-isn';当状态更改时,t将更新
我有一个反应组件,其设置如下:Javascript ReactJS:element-isn';当状态更改时,t将更新,javascript,reactjs,Javascript,Reactjs,我有一个反应组件,其设置如下: 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
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>
);
}
}
导出默认类FormDialog扩展React.Component{
构造函数(){
超级();
this.state={allowedToDelete:false};
}
onChange(事件){
if(event.target.value.match(this.targetName)){
log(“这是一场比赛!”);
this.state={allowedToDelete:true};
console.log(this.state);
}否则{
this.state={allowedToDelete:false};
}
}
render(){
const{profile,deleteUser,handleDialogClose,…other}=this.props;
this.targetName=`${profile.firstName}${profile.lastName}`;
console.log({…其他})
返回(
是否删除此用户?
allowedToDelete:{String(this.state.allowedToDelete)}
取消
删除用户!
);
}
}
(我在这里使用的是材质ui的表单对话框组件)
如上所述,系统会提示用户键入要删除的配置文件的全名;如果它们与名称匹配,“删除用户!”按钮应变为非禁用状态
我的onChange()
事件正在工作,当我键入正确的名称时,我看到它是匹配的在我的控制台中的code>和this.state
日志显示this.state.allowedToDelete===true
但是,我的渲染函数的allowedToDelete:{String(this.state.allowedToDelete)}
以及我的按钮的disabled={!this.state.allowedToDelete}
都保持false
我做错了什么?对于我对状态的理解,我是一个新手,可能会感到困惑,但我已经尝试使用直接附加到此
而不是状态的变量来实现这一点,但这也不起作用…您需要调用设置状态
。你可以读到它。这就是告诉react组件触发生命周期以显示新状态的原因
this.setState({allowedToDelete: false});
您需要调用setState
。你可以读到它。这就是告诉react组件触发生命周期以显示新状态的原因
this.setState({allowedToDelete: false});
啊,我不知道,我是个傻瓜。谢谢啊,我不知道,我是个傻瓜。谢谢React示例和文档清楚地概述了如何更改状态。使用setState。React示例和文档清楚地概述了如何更改状态。使用setState。