export default class Parent extends React.Component {
render() {
return(
<div>
//第一步:可以看作父向子传值的方式,
//传一个函数过去(该函数的作用就是把某个值赋给this.child)
<Child onRef={this.onRef} />
<button onClick={this.click} >click</button>
</div>
)
}
//该函数的作用就是把某个值赋给this.child
onRef=(ref)=>{
this.child=ref
}
//父中调用子组件的方法
click=()=>{
this.child.childCLick()
}
}
第二步:
class Child extends Component {
componentDidMount(){
//通过props接收父组件传来的方法,并将自身this作为参数传入并执行。
//这样父组件中的this.child就代表这个子组件Child了。
this.props.onRef(this)
}
myName = () => alert('子组件fn')
render() {
return ('ch')
}
}