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

组件间通信除了props外还有onRef方法,不过React官方文档建议不要过度依赖ref。

//父组件
import React, { Component } from "react";
import Child from "./Child";

class Dad extends Component {
    constructor(props) {
        super(props);
        this.state = {
            arr:["暴富","暴瘦"],
            txt:"我是尼爸爸"
        }
    }

    onRef=(ref)=>{
        this.Child=ref;
    }

    click=()=>{
        this.Child.childFn();
    }

    render() {
        return (
            <div>
                <Child onRef={this.onRef}></Child>
                <button onClick={this.click}>父组件调用子组件中的方法</button>
            </div>
        )
    }
}

export default Dad;

//子组件
import React, { Component } from "react";

class Child extends Component {
    constructor(props){
        super(props);
    }

    componentDidMount() {
        this.props.onRef(this)
    }

    childFn=()=>{
        console.log("我是子组件中的方法")
    }

    render() {
        return (
           <div>
           </div>
        )
    }
}

export default Child;

原理:

当在子组件中调用onRef函数时,正在调用从父组件传递的函数。this.props.onRef(this)这里的参数指向子组件本身,父组件接收该引用作为第一个参数:onRef = {ref =>(this.child = ref)}然后它使用this.child保存引用。之后,可以在父组件内访问整个子组件实例,并且可以调用子组件函数。