代码之家  ›  专栏  ›  技术社区  ›  JVG

ReactJS:状态更改时不更新元素

  •  -1
  • JVG  · 技术社区  · 7 年前

    我有一个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>
        );
      }
    }
    

    如上所述,系统将提示用户键入要删除的配置文件的全名;如果用户与该名称匹配,则输入“delete user!”按钮应变为未禁用。

    我的 onChange() 事件正在工作,当我键入正确的名称时 It's a match! this.state 表明 this.state.allowedToDelete === true .

    但是,我的渲染函数 allowedToDelete: {String(this.state.allowedToDelete)} 还有我的纽扣 disabled={!this.state.allowedToDelete} false .

    this 而不是国家,这也不起作用。。。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Chance Smith    7 年前

    你需要打电话 setState in the react docs . 这就是告诉react组件触发生命周期以显示新状态的原因。

    this.setState({allowedToDelete: false});