2016-10-21 32 views
1

私は基本的にフォームである親コンポーネントを持っています。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> 
); 
} 
} 

子の一例です。

どうすればいいですか?事前に

おかげ

答えて

1

クローンReact.cloneElementを使用して、新しいref小道具と全体の子どもたち。送信時には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>

関連する問題