首页 > 解决方案 > 如何从父 onSubmit 触发子组件验证 - 反应

问题描述

我看到了一个角度的解决方案,但我希望能够用 React 来做到这一点。我已经能够从孩子那里获取数据到父母进行验证,但是当字段可能为空时,我仍然无法触发表单提交的验证。

我的子组件的所有验证都包含在子组件中,并由 onblur 或 onchange 事件触发。有什么建议我该怎么做?

class MainForm extends Component {

  handleSubmit(e) {
    e.preventDefault();
  }
  render() {
    const nameFields = [
      {
        id: 'firstame', type: 'text', name: 'firstname', label: 'First name', required: true,
      },
      {
        id: 'lastName', type: 'text', name: 'lastname', label: 'Last name', required: true,
      },
    ];
    return (
      <div>
        <form onSubmit={e => (this.handleSubmit(e))} noValidate>
          <div className="form__field--background">
            <div>
              {
                nameFields.map(element => (
                  <div key={element.id} className="form__field--wrapper">
                    <InputField
                      type={element.type}
                      id={element.name}
                      name={element.name}
                      required={element.required}
                      placeholder={element.placeholder}
                      label={element.label}
                      pattern={element.pattern}
                    />
                  </div>
                ))
              }
            </div>
          </div>

          <button type="submit" className="btn btn--red">Update Preferences</button>
        </form>

      </div>
    );
  }
}
export default MainForm;




class InputField extends Component {
  constructor() {
    super();
    // this.inputField = React.createRef();
    this.validateField = this.validateField.bind(this);
    this.state = {
      valid: null,
      message: '',
    };
  }
  /**
   * Calls helper function to validate the input field
   * Sets the the state for the validation and validation message
   */
  validateField(e) {
    const props = {
      field: e.target,
      label: this.props.label,
      required: this.props.required,
      min: this.props.min,
      max: this.props.max,
      pattern: this.props.pattern,
      emptyError: this.props.emptyFieldErrorText,
      invalidError: this.props.invalidErrorText,
    };
    let validation = this.state;
    // helper function will return an updated validation object
    validation = fieldValidation(props, validation);
    this.setState(validation);

    return validation;
  }

  /**
   * Calls validateField method if field is a checkbox.
   * Calls inputHandler callback.
   * Handles the callback isValid state to parent component.
   */
  handleInputChange(e) {
    if (e.target.required && e.target.type === 'checkbox') {
      this.validateField(e);
    }
    this.handleInputValidation(e);
  }

  handleInputValidation(e) {
    if (typeof this.props.isValid === 'function') {
      this.props.isValid(this.validateField(e), this.props.name, e.target.value);
    }
  }

  handleOnBlur(e) {
    if (e.target.type !== 'checkbox') {
      this.validateField(e);
    }
  }
  render() {
    return (
      <div>
        <label>
          {this.props.label}
        </label>
        {this.props.helpText &&
        <p className="form-help-text">{this.props.helpText}</p>
        }
        <input
          type={this.props.type}
          id={`field-input--${this.props.id}`}
          name={this.props.name && this.props.name}
          required={this.props.required && this.props.required}
          placeholder={this.props.placeholder && this.props.placeholder}
          onBlur={e => this.handleOnBlur(e)}
          onChange={e => this.handleInputChange(e)}
        />
        {this.state.valid === false &&
            <span className="form-error">
              {this.state.message}
            </span>
        }
      </div>
    );
  }
}


export default InputField;

标签: reactjs

解决方案


您可以通过让子组件让父组件知道它存在于早期生命周期方法中来确保父组件知道子组件。

IE:

class ChildComponent extends React.Component {
    componentWillMount() {
        this.props.tellParentEntryExists();
    }
}

这意味着当涉及到验证时,父级有一个要验证的条目?


推荐阅读