ReactJS-使用onBlur验证电子邮件字段

时间:2018-12-11 12:07:30

标签: javascript reactjs material-ui onblur

我有一个用于电子邮件的MaterialUI文本字段,当用户离开该字段时,该字段会验证输入。为此,我在onBlur上使用了一个函数。我想显示一个使用helpertext的错误消息。

电子邮件代码字段:

<TextField
    margin="dense"
    id="emailAddress"
    name="email"
    label="email"
    type="email"
    onChange={onChange}
    onBlur={validateEmail}
    value={email}
    error={validEmail}
    helperText={validEmail ? 'Please enter a valid Email' : ' '}
    fullWidth
 />

validEmail变量在功能组件内部初始化如下:

let validEmail = false;

validateEmail与以下组件相同:

const validateEmail = () => {
    if (!email || invalidEmail(email)) {
      validEmail = true;
    } else {
      validEmail = false;
    }
};

但是它不起作用,并且不会显示错误消息。我在这里可能会错过什么?检查invalidEmail的条件确实得到执行。

2 个答案:

答案 0 :(得分:0)

invalidEmail(email)返回true时,您将true分配给validEmail。您确定这不是逻辑错误吗?

答案 1 :(得分:0)

我认为正确的方法是使用组件的内部状态:

class EmailComponent extends React.Component {
  state = {
    validEmail: false,
    email: '',
  };

  onChange = (e) => {
    ...
    this.setState({
      email: e.target.value
    });
  }

  validateEmail = (e) => {
    const email = e.target.value;
    if (!email || invalidEmail(email)) {
      this.setState({
        validEmail: true,
      });
    } else {
      this.setState({
        validEmail: false,
      });
    }
  }

  render () {
    const { validEmail, email } = this.state;

    return (
      <TextField
        margin="dense"
        id="emailAddress"
        name="email"
        label="email"
        type="email"
        onChange={this.onChange}
        onBlur={this.validateEmail}
        value={email} //I think you should also set email as a state
        error={validEmail}
        helperText={validEmail ? 'Please enter a valid Email' : ' '}
        fullWidth
      />
    );
  }
}

在无状态组件内更改变量的值将无法实现所需的功能,因为除非更改道具或状态之一,否则该组件不会再次呈现。

编辑:使用父组件处理状态

class ParentComponent extends React.Component {
  state = {
    validEmail: false,
    email: '',
  };

  onChange = (e) => {
    this.setState({
      email: e.target.value
    });
  }

  validateEmail = (e) => {
    const email = e.target.value;
    if (!email || invalidEmail(email)) {
      this.setState({
        validEmail: true,
      });
    } else {
      this.setState({
        validEmail: false,
      });
    }
  }

  render () {
    const { validEmail, email } = this.state;

    return (
      <ChildComponent 
        email={email}
        validEmail={validEmail}
        onChange={this.onChange}
        validateEmail={this.validateEmail}
      />
    );
  }
}

const ChildComponent = (props) => (
  <TextField
    margin="dense"
    id="emailAddress"
    name="email"
    label="email"
    type="email"
    onChange={props.onChange}
    onBlur={props.validateEmail}
    value={props.email}
    error={props.validEmail}
    helperText={props.validEmail ? 'Please enter a valid Email' : ' '}
    fullWidth
  />
);