reactjs - How to call `this.props.children` 's function from parent component? -


there question relative, different

call child method parent

call child function parent component in react native

https://github.com/kriasoft/react-starter-kit/issues/909

they need import child in parent file.

but how set ref this.props.children ???

purpose

i want call child method in parent , parent common wrapper require child specific function . child dynamic,

  1. child

    class child extends react.component {   method() {     alert(1111);   }   render() {      return (       <div>         ....       </div>     );   } } 
  2. parent

    import react 'react' // can not import child here // import child './child'    class parent extends react.component {   onclick = () => {     this.props.children.method() // stuff, not work   }   render() {      const {children} = this.props;     return (       <div>         {children}         <button onclick={this.onclick}></button>       </div>     );   } } 
  3. index.js

    <parent>    <child/ > </parent> 

parent can access child this.props.children, don't want pass child's method parent in index.js , or define child's method in index.js.

in other word:

  1. child keep child's code.(for example, form submit logic)

  2. parent common wrapper. (for example, dialog used wrap form)

  3. index.js don't care them

any idea?

thanks @panther 's comment, work around using react.cloneelement :

  1. child

    class child extends react.component {    handlesubmit() {     //...   }    render() {      return (       <div>         ....       </div>     );   } } 
  2. parent

    import react 'react'  class parent extends react.component {    onclick() {     // fist child need have handlesubmit     this.refs.child0.handlesubmit()     this.toggledialog()   }    render() {      const children = react.children.map(this.props.children,       (child, index) => react.cloneelement(child, {         ref : `child${index}`       })      );      return (         <div>           <dialogcontent>             {children}           </dialogcontent>         <button onclick={this.onclick}></button>       </div>     );   } } 
  3. index.js

    <parent>    <child/ > </parent> 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -