我制作了一个注册页面,并希望它在提交之前进行一些验证。所以,我放入event.preventDefault了我的handleSubmit 函数。event.preventDefault是为了防止默认功能,所以如果表单为空,则不会提交。但是,在我填满所有空白后,它就可以提交。我的问题还是event.preventDefault在handleSubmit函数填空后,为什么可以提交表单?或者,如果用户填写所有空白,该功能event.preventDefault将被禁用?
谢谢!
export default function RegisterPage() {
const [values, setValues] = useState({
userName: "",
nickName: "",
password: "",
});
const [errors, setErrors] = useState({});
const [apiResError, setApiResError] = useState("");
const handleSubmit = (e) => {
setApiResError("");
e.preventDefault();
registerAccount(values.userName, values.nickName, values.password).then(
(res) => {
console.log(res);
}
);
};
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
const handleFocus = (e) => {
const { name } = e.target;
setErrors({ ...errors, [name]: "" });
};
return (
<RegisterPageContainer>
<RegisterPageTitle>Register</RegisterPageTitle>
{apiResError && <div>{apiResError}</div>}
<RegisterForm onSubmit={handleSubmit}>
<InputWrapper>
<UserNameInput
name="userName"
type="text"
placeholder="Username"
onChange={handleChange}
value={values.userName}
onFocus={handleFocus}
/>
</InputWrapper>
{errors.userName && <div>{errors.userName}</div>}
<InputWrapper>
<NickNameInput
name="nickName"
type="text"
placeholder="Nickname"
onChange={handleChange}
value={values.nickName}
onFocus={handleFocus}
/>
);
}
回首忆惘然
相关分类