React 父组件调用子组件的方法

import React, {Component} from 'react';

export default class Parent extends Component {
render() {
return(
<div>
//1
<Child onRef={this.onRef} />
<button onClick={this.click} >click</button>
</div>
)
}
//2
onRef = (ref) => {
this.child = ref
}
//3
click = (e) => {
this.child.myName()
}

}

class Child extends Component {
componentDidMount(){
//4
this.props.onRef(this)
}

myName = () => alert('xiaohesong')

render() {
    return ('woqu')
}

}

推荐阅读更多精彩内容