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

// 父组件
class Parent extends Component {
    handleChild = ()=> {
        this.$Child.childConsole();    // 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);    // 调用父组件传入的函数,把自身赋给父组件
    }
    // 定义一个子组件方法
    childConsole = ()=> {
        console.log('我是子组件方法')
    }
    render() {
        return (
      <div>

      </div>
    ) }

 

posted @ 2020-08-05 18:31  a茶色  阅读(8840)  评论(0)    收藏  举报