React JS:如何从其父级调用自定义输入组件的验证方法

时间:2019-01-26 12:45:58

标签: javascript reactjs

我已经编写了一个自定义的Input类组件。

class Input extends React.Component {
  validate = () => { 
    // validation logic
  }

  handleChange = () => {this.validate()}

  render () {
    return <input onChange={this.handleChange} name={this.props.name} type={this.props.type}/>
  }
}

Form组件中,我像这样使用它。

class Form extends React.Component {

  handleSubmit () => {
    // trigger Input validation here
  }

  render () {
    return <form onSubmit={this.handleSubmit}>
      <Input name="abc" type=""/>
      <Input name="abc" type="password"/>
    </form>
  }
}

Input组件中嵌套了超过20个Form组件。我的问题是,提交表单后,如何触发来自上级Form组件的Input组件的验证?由于我有很多Input组件,因此我需要一种方法来调用每个Input实例的所有验证方法。

2 个答案:

答案 0 :(得分:2)

父组件应具有子代的ref才能访问其方法:

  refs = {
    foo: React.createRef(),
    bar: React.createRef()
  }

  handleSubmit () => {
    for (const [refName, ref] of Object.entries(this.refs)) {
      const isValid = ref.current.handleSubmit();
      // ...
    }
  }

  render () {
    return <form onSubmit={this.handleSubmit}>
      <Input ref={this.refs.foo} name="foo"/>
      <Input ref={this.refs.bar} name="bar"/>
    </form>
  }

如果有很多输入,可以通过自动注册具有与name属性匹配的相应名称的引用来使代码成为DRYer。

答案 1 :(得分:0)

请尝试以下代码从子组件中调用函数。

class Parent extends React.Component {
    triggerChildAlert(){
        this.refs.child.showAlert();
    }

    handleSubmit () => {
       this.refs.child.validate ();
    }

    render() {
        return (
                <div>
                   {/* Note that you need to give a value to the ref parameter, 
                       in this case child*/}
                   <Child ref="child" />
                   <button onClick={this.handleSubmit}>Click</button>
                </div>
            );
        }
    }


class Child extends React.Component {
    validate () {

    }

    render() {
        return (

        );
    }
 }