reactjs parent trigger子组件

时间:2016-10-21 10:23:49

标签: javascript forms reactjs components

我有一个父组件,基本上是一个Form。

export default class Parent extends Component{
  submitInput(event){
    ...call Children
  }

  render(){
    return(
     <div>
      <form className="form-horizontal"  onSubmit= {this.submitInput.bind(this)}>
       {this.props.children}
       <button type="submit">Submit</button>
    </div>
  </form>
</div>);
 }}

子项可以是不同类型的输入,所有输入都使用名为validate()的通用函数。

以下是儿童的一个例子

export default class Child extends Component{

validate(){
    ..validate stuff
 }


render(){
  return(
      <div className="form-group">
              <textarea ref={this.props.name} />
      </div>
 );
}
}

On提交父组件我希望使用他们的validate()函数验证所有子输入。

我该怎么做?

提前致谢

1 个答案:

答案 0 :(得分:1)

使用ref使用新React.cloneElement道具克隆整个孩子。在提交时,使用ref来访问孩子的方法。

请参阅下面的示例。如果需要更多详细说明,请发表评论。

希望这有帮助!

&#13;
&#13;
class Form extends React.Component{
  submitInput(){
    this.childrenClone.forEach((el) => {
      var r = el.ref //use the ref to access the child's methods
      this.refs[r].validate()
    })
  }
  
  render() {
    this.childrenClone = React.Children.map(this.props.children,
     (child) => React.cloneElement(child, {
       ref: Math.random().toString(36).slice(-5) //add a random string as a ref
     })
    )
    
    return <div>
      <form className="form-horizontal"  onSubmit={this.submitInput.bind(this)}>
       {this.childrenClone}
       <button type="submit">Submit</button>
       </form>
    </div>
  }
}


class Child extends React.Component{
  validate(){
    console.log('validate textarea') //on validate log this
  }
  
  render() {
    return <div className="form-group">
          <textarea />
      </div>
  }
}

class ChildInput extends React.Component{
  validate(){
    console.log('validate Input') //on validate log this
  }
  
  render() {
    return <div className="form-group">
          <input type="text" />
      </div>
  }
}
class Parent extends React.Component{
  render(){
    return <Form>
      <Child/>
      <Child/>
      <ChildInput/>
      <ChildInput/>
    </Form>
  }
}

ReactDOM.render(<Parent/>, document.getElementById('app'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;

相关问题