1.父组件内,执行方法
onRef = ref => {
this.childElement = ref;
};
把方法传给子组件
<ChildElement
onRef={this.onRef}
/>
2.子组件内
componentDidMount(){
const { onRef } = this.props;
onRef(this);
}
childFn = () => {
console.log(‘子方法’)
}
父组件方法内 this.childElement就是子组件的this,所以可以拿到子组件的state(this.childElement.state),props(this.childElement.props),调用子组件的方法(this.childElement.childFn())。