// 父组件
class Parent extends Component {
handleChild = ()=> {
this.$Child.childMethod(); // this上就有了子组件
}
render() {
return (
<div>
<Child onRef={(ref)=> {this.$Child=ref}} />
<button onClick={this.handleChild}>调用子组件方法</button>
</div>
)
}
}
// 子组件
class Child extends Component {
componentDidMount() {
this.props.onRef(this); // 调用父组件传入的函数,把自身赋给父组件
}
// 定义一个子组件方法
childMethod = ()=> {
alert('我是子组件中的方法!');
}
render() {
return (<div></div>)
}
}