输入验证错误消息不会在React中消失

时间:2019-07-12 14:44:35

标签: javascript reactjs validation input modal-dialog

当您要编辑用户时,我使用的是React Modal。但是,当我取消Modal并在其上单击时,两个错误消息仍在输入字段下方。我该如何解决?

<Modal isOpen={this.state.editUserModal}
       toggle={this.toggleEditUserModal.bind(this)}>
    <ModalHeader toggle={this.toggleEditUserModal.bind(this)}>
        Edit user
    </ModalHeader>
    <ModalBody>
        <FormGroup>
            <Label for="name">Name</Label>
            <Input required={true} id="name" value=
                {this.state.editUserData.name} onChange={(e) => {
                let {editUserData} = this.state;

                editUserData.name = e.target.value;

                this.setState({editUserData});
            }}/>
            <div style={{fontSize: 12, color: 'red'}}>{this.state.nameError}</div>
        </FormGroup>
        <FormGroup>
            <Label for="job">Job</Label>
            <Input required={true} id="job" value={this.state.editUserData.job} onChange={(e) => {
                let {editUserData} = this.state;

                editUserData.job = e.target.value;

                this.setState({editUserData});
            }}/>
            <div style={{fontSize: 12, color: 'red'}}>{this.state.jobError}</div>
        </FormGroup>

    </ModalBody>
    <ModalFooter>
        <Button color="primary" onClick={this.updateUser.bind(this)}>Update User</Button>{' '}
        <Button color="secondary" onClick={this.toggleEditUserModal.bind(this)}>Cancel</Button>
    </ModalFooter>
</Modal>

状态:

state = {
  users: [],
    name: '',
    job: '',
    nameError: '',
    jobError: '',
    editUserData: {
      id: '',
        name: '',
        job: ''
    }
};

2 个答案:

答案 0 :(得分:0)

关闭模态后,您必须重置在模态视图上使用的状态键。

重置 toggleEditUserModal 方法中的状态键

编辑:添加了示例

toggleEditUserModal() {
    // ... your current logic

   // Set state below only in case modal has been closed
   this.setState({ 
       nameError: null, 
       jobError: null 
   })
}

答案 1 :(得分:0)

在toggleEditUserModal中调用父函数以刷新父状态