2016-10-21 86 views
1

我有一个父组件,它基本上是一个Form。reactjs父触发子组件

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> 
); 
} 
} 

在我想用自己的validate()函数验证所有输入儿童的父Component提交的一个例子。

我该怎么做?

在此先感谢

回答

1

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

请看下面的例子。如果需要更详细的说明,请发表评论。

希望这会有所帮助!

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'))
<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>

相关问题