如果它无效,我想防止反应路由器从表单转移过来。 Using和prompt不能令人满意,因为我想完全阻止用户导航到新路线,直到表单有效为止(而提示似乎总是向用户提供继续操作的选项),并希望在我的页面上显示错误消息,而不是提示性提示。
如何在没有提示的情况下防止这种过渡?
我的表单:
<form>
<div>
<label>Name: </label>
<input
type="text"
name="name"
id="name"
onChange={this.handleChange}
autoComplete="name"
/>
</div>
<div>
<label>Email: </label>
<input
type="text"
name="email"
id="email"
onChange={this.handleChange}
autoComplete="email"
/>
</div>
<div>
<label>Password: </label>
<input
type="password"
name="password"
id="password"
onChange={this.handleChange}
autoComplete="new-password"
/>
</div>
<br />
<div>
<!-- HERE IS THE LINK I WANT TO DISABLE IN CASE OF INVALID FORM -->
<Link when={this.state.formIsValid} to="/F2">
<button
onClick={() => {
if (this.formIsValid()) {
this.props.updatePurchaseRecord({
name: this.state.name,
email: this.state.email,
password: this.state.password,
purchase_id: this.props.purchase_id
});
}
}}
>
Next
</button>
</Link>
</div>
</form>
我的formIsValid函数在单击“下一步”按钮后立即运行:
formIsValid() {
let isValid = true;
let formErrors = { name: "", email: "", password: "" };
// validate name
if (this.state.name === "") {
isValid = false;
formErrors.name = "Name is required";
}
// validate email
if (this.state.email === "") {
isValid = false;
formErrors.email = "Email is required";
}
// validate password
if (this.state.password === "") {
isValid = false;
formErrors.password = "Password is required";
}
this.setState({ formErrors });
return isValid;
}
答案 0 :(得分:1)
如果表单无效,为什么不仅仅呈现按钮的禁用版本?例如:
formIsValid ? <RealButton /> : <DisabledButton />