class Parent extends React.Component {
render() {
return (
<div className="parent">
{/* 把子组件实例(ref)传递给this.child */}
<Child
onRef={ref => {
this.child = ref
}}
/>
{/* 执行子组件实例的方法 */}
<button onClick={this.child.speak}>click</button>
</div>
)
}
}
class Child extends React.Component {
constructor(props) {
super(props)
// 将当前实例(this)传递给父组件
props.onRef(this)
}
speak() {
alert('hello there')
}
render() {
return <div className="child">child</div>
}
}