reactjs - How to call `this.props.children` 's function from parent component? -
there question relative, different
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,
child
class child extends react.component { method() { alert(1111); } render() { return ( <div> .... </div> ); } }
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> ); } }
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:
child
keepchild
's code.(for example, form submit logic)parent
common wrapper. (for example, dialog used wrap form)index.js don't care them
any idea?
thanks @panther 's comment, work around using react.cloneelement :
child
class child extends react.component { handlesubmit() { //... } render() { return ( <div> .... </div> ); } }
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> ); } }
index.js
<parent> <child/ > </parent>
Comments
Post a Comment