如何从父onSubmit触发子组件验证 - 反应

时间:2018-06-07 15:17:40

标签: reactjs

我看到了一个有角度的解决方案,但我希望能够用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;

1 个答案:

答案 0 :(得分:0)

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

即:

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

这意味着在验证时,父母有一个验证条目?