import React, {Component} from 'react';
export default class Parent extends Component {
render() {
return(
<div>
<Child onRef={this.onRef} /> // 这里通过onRef调用子类和父类进行绑定
<button onClick={this.click} >click</button>
</div>
)
}
onRef = (ref) => { //父类onRef:将ref参数赋给父类this.child
this.child = ref
}
click = (e) => {
this.child.myName() ; // 父类通过this.child调用子类的myName方法。
}
}
class Child extends Component {
componentDidMount(){
this.props.onRef(this) //需要父类调用子类方法时,必须有这行代码。
}
myName = () => alert('xiaohesong') //子类方法
render() {
return ('woqu')
}
}