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

父组件调用子组件的方法 React v16.3.0 及以后版本使用

import React, {Component} from 'react';

export default class Parent extends Component {
    render() {
        return(
            <div>
                <Child onRef={this.onRef} />
                <button onClick={this.click} >click</button>
            </div>
        )
    }

    onRef = (ref) => {
        this.child = ref
    }

    click = (e) => {
        this.child.myName()
    }

}

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

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

    render() {
        return ('woqu')
    }
}

参考链接:https://www.cnblogs.com/universe-cosmo/p/10969351.html

原文地址:https://www.cnblogs.com/ITCoNan/p/11630816.html