There are some question relative, but completely different
Call child function from parent component in React Native
https://github.com/kriasoft/react-starter-kit/issues/909
They all need import Child
in Parent
file.
But how to set ref to this.props.children
???
Purpose
I want to call Child
method in Parent
, Parent
is a common wrapper which require a Child
with specific function . Child
is dynamic,
Child
class Child extends React.Component { method() { alert(1111); } render() { return ( <div> .... </div> ); } }
Parent
import React from 'react' // can not import Child here // import Child from './Child' class Parent extends React.Component { onClick = () => { this.props.children.method() // do stuff, but not work } render() { const {children} = this.props; return ( <div> {children} <button onClick={this.onClick}></button> </div> ); } }
index.js
<Parent> <Child/ > </Parent>
Parent
only can access Child
by this.props.children
, I don't want pass Child
's method to Parent
in index.js , or define Child's method in index.js.
In other word:
Child
keep allChild
's code.(For example, a form with submit logic)Parent
is a common wrapper. (For example, a dialog used to wrap a form)Index.js don't care them
Any idea?