react 父类通过onRef调用子类方法

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')
    }
}

 


版权声明:本文为zb0002011原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。