• 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保存引用。之后,可以在父组件内访问整个子组件实例,并且可以调用子组件函数。

  • 相关阅读:
    B
    A
    UVA
    马的移动(BFS) 详细注释 一个具有情怀的题目
    JAVA JDK 环境变量配置--简单图解
    linux系统(rpm与deb环境),JAVA JDK的配置
    Jmeter接口测试+压力测试+环境配置+证书导出
    LR访问Https接口
    GitHub linux 提交文件及403错误处理
    random模块写的验证码
  • 原文地址:https://www.cnblogs.com/ranyonsue/p/14582449.html
Copyright © 2020-2023  润新知