这似乎是一件简单的事情,但经过反复摆弄,我不知道出了什么问题。我是React的菜鸟,请原谅我。
我有一个登录表单。像大多数登录表单一样,它要求输入用户名和密码。然后它有一个提交按钮。我的理解是,如果状态发生变化,组件将重新渲染。我在更新状态的每个输入字段上都有onchange
事件。因此,如果该字段为空,则按按钮提交,我希望该错误会显示出来。如果我填写一个字段,由于状态更改,我希望错误消息消失。我误会了吗
这是我的事件处理程序:
handleLogin(event) {
event.preventDefault();
if (this.state.username == '') {
this.setState({usernameError: "Need to enter a username"})
return;
}
if (this.state.password == '') {
this.setState({passwordError: "Need to enter a password"})
return;
}
}
以及形式:
render() {
return(
<form className="login-form">
<h1 className="login-form__header"><FontAwesomeIcon icon="key" className="registration-form__icon"/><i className="fal fa-route-highway"></i>Log Into Your Account</h1>
<input type="text" name="username" placeholder="Username" className="login-form__input" onChange={(event,newValue) => this.setState({username:newValue})}/>
{this.state.usernameError &&
<p class="login-form__error"><FontAwesomeIcon icon="times-circle"/> {this.state.usernameError}</p>
}
<input type="password" name="password" placeholder="Password" className="login-form__input" onChange={(event,newValue) => this.setState({password:newValue})}/>
{this.state.passwordError &&
<p class="login-form__error"><FontAwesomeIcon icon="times-circle"/> {this.state.passwordError}</p>
}
<button className="login-form__button" onClick={this.handleLogin}>Log Into Your Account</button>
</form>
);
}
最佳答案
是的,但是如果字段不为空,则您从未配置任何逻辑来清除错误。当前,没有任何逻辑设置可将usernameError
和passwordError
变回空字符串或空值。
您可能会产生以下印象:重新渲染state
时将其清除,但事实并非如此。重新渲染之前的state-object
仍然存在,只是更改了您在this.setState()
中最后更新的键/值对。
尝试这个:
handleLogin(event) {
event.preventDefault();
const { username, password } = this.state
this.setState({
...this.state,
usernameError: username.length > 0 ? "" : "Need to enter a username",
passwordError: password.length > 0 ? "" : "Need to enter a password"
})
}
这是一个正常工作的沙箱,带有经过修改的代码版本。 (我删除了FontAwesomeIcons)。 https://codesandbox.io/s/cool-meninsky-y9r4y
关于javascript - 填写字段后,为什么我的错误消息没有更新? ( react ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57106306/