reactjs - 带有按钮状态的 FormValidation
问题描述
在我的 React 应用程序中,我有一个组件调用<ComingSoonForm/>
在里面,我有一个 TextInputField。如果电子邮件有效,则通知按钮可以。如果电子邮件无效,通知按钮将被禁用。
这是我的组件文件:
import React, { Component } from "react";
import { TextInputField, toaster, Button, } from "evergreen-ui";
import Box from 'ui-box';
import { validateEmail } from "../FormValidation/FormValidator";
class ComingSoonForm extends Component {
constructor(props) {
super(props);
this.state = {
emailErr: {
status: true,
value: ""
},
email: "",
isDisabled: true,
};
this.handleSubmit = this.handleSubmit.bind(this);
this.checkFormStatus = this.checkFormStatus.bind(this);
}
handleEmailInput = e => {
const email = e.target.value;
this.setState({ email: email});
console.log(this.state.email);
this.checkFormStatus();
};
handleSubmit() {
if (this.checkFormStatus()) {
alert("Form is OK")
}
}
checkFormStatus() {
// form validation middleware
const { email } = this.state;
const emailErr = validateEmail(email);
if (!emailErr.status) {
this.setState({isDisabled:false})
return true;
} else {
this.setState({
emailErr,
});
return false;
}
}
render() {
return (
<div>
<Box className="welcomePageWelcomeInnerLoginButton">
<TextInputField
marginTop={15}
width={200}
onChange={this.handleEmailInput}
value={this.state.email}
type="email"
placeholder="Your email-address"
inputHeight={40}
/>
</Box>
<Button height="40" appearance="primary" marginBottom={5} className="welcomePageWelcomeInnerLoginButtonWidth" disabled={this.state.isDisabled} onClick={this.handleSubmit}>Notify Me</Button>
</div>
);
}
}
export default ComingSoonForm;
但是这种情况不能正常工作。因此,当Functionconsole.log(this.state.email)
中的命令handleEmailInput
运行时,我在控制台中得到以下数据:
我输入一个字母 (t),我得到:
//ComingSoonForm.js:25
我输入第二个字母 (t),我得到:
t //ComingSoonForm.js:25
t //FormValidator.js:10
为什么我必须输入两个字母才能在控制台中显示一个?
解决方案
setState 是异步的,您可以将回调方法作为第二个参数传递,如下所示:
handleEmailInput = e => {
const email = e.target.value;
this.setState({ email: email }, () => console.log(this.state.email));
this.checkFormStatus();
};
推荐阅读
- javascript - 如何在 Todo 项目上创建编辑选项,仅使用纯 JavaScript
- hiveql - 在 HIVE SQL 中将字符串转换为时间
- escaping - Azure 数据工厂转义字符错误
- javascript - 如何创建在 JS 中按下按钮时显示的微调器动画?
- java - 如何在 Java 中成功地从书中删除标签?
- javascript - 组件加载后运行 API 获取请求
- javascript - 如何在特定值为 1 的 jQuery.each 中计数
- android - Android StringRequest 未捕获 Laravel 错误
- python - Python在类文件对象中重写`read()`类方法
- ios - CloudKit正确接收和存储时间,查询时返回UTC时间