// 父組件
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>)
}
}