我该如何在课堂上简化我的方法?

时间:2018-07-13 00:30:54

标签: reactjs

我如何使用可以接收状态并进行更改的函数来简化我的方法? 目的是使方法最干净。 还处理asicronic验证:(

onBlur(e){
  const field = e.target.name;
  const value = e.target.value;
  let errors = this.state.errors;
  let validFields = this.state.validFields;
  let invalid = this.state.invalid;


  if (edit && field === 'username' && edit.username === value) {
    return;
  }


  if (field === 'password2') {
    if (value !== this.state.password1){
      //console.log('password no conciden');
      errors[field] = 'password no conciden';
      validFields[field] = '';
      invalid = true;
    }else if (value === this.state.password1){
      validFields[field] = true;
      validFields['password1'] = true;
      errors[field] = "";
      invalid = false;

    }
    this.setState({validFields, errors, invalid});

    //return;
  }
  // Cheack field username
  this.props.ifExistsField("UsersModel", field, value).then((response) => {

    if(response.data[field] !== true){
      errors[field] = response.data[field];
      validFields[field] = '';
      invalid = true;

    } else {
      validFields[field] = response.data[field];
      errors[field] = "";
      invalid = false;


    }
    this.setState({validFields, errors, invalid});
  });

}

这是一种可以使用方法onBlur进行验证的格式,但是非常大。 谢谢帮我!

1 个答案:

答案 0 :(得分:0)

组件表格。

Golden Eagle

功能验证,将此作为参数传递。

onBlur(e){
  onBlurValidator(e, this);      
}

看起来更好!