react中直接调用子组件的方法(非props方式)


我们都知道在 react中,若要在父组件调用子组件的方法,通常我们会采用在父组件定义一个方法,作为props转给子组件,然后执行该方法,可以获取到子组件传回的参数以得到我们的目的。

显而易见,这个执行是需要去主动触发的。

那有没有一种方式,方法在子组件定义好,可以直接在父组件去调用呢?

答案是必然的。

上代码^ - ^

import React, {Component} from "react";
import { Button } from "antd";

//父组件
export default class Parent extends Component {
    render() {
        return(
            <div>
          <p>这是父组件</p>
                <Child triggerRef={this.bindRef} />
                <Button type="primary" onClick={this.btnClick} >click</Button>
            </div>
        )
    }

    bindRef = ref => { this.child = ref }

    btnClick = () => {
        this.child.getValuefromChild()
    }

}
//子组件
class Child extends Component {
    componentDidMount(){
        this.props.triggerRef(this)
    }
  //这是子组件的方法
    getValuefromChild = () => console.log("this is child value.")

    render() {
        return <div>这是子组件</div>
    }
}

是不是瞬间就风清月朗了~~


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM