首页 > 解决方案 > 带有按钮状态的 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

为什么我必须输入两个字母才能在控制台中显示一个?

标签: reactjs

解决方案


setState 是异步的,您可以将回调方法作为第二个参数传递,如下所示:

handleEmailInput = e => {
  const email = e.target.value;
  this.setState({ email: email }, () => console.log(this.state.email));
  this.checkFormStatus();
};

推荐阅读