首页 > 其他分享 >[email protected](12)ref 转发-forwardRef

[email protected](12)ref 转发-forwardRef

时间:2024-05-28 22:30:50浏览次数:14  
标签:12 return 16 React forwardRef props 组件 ref

目录

1,介绍

上篇文章中提到,ref 只能对类组件使用,不能对函数组件使用。

ref 转发可以对函数组件实现类似的功能。

使用举例

import React, { Component } from "react";

function CompA(props, ref) {
    return (
        <h1>
            <div ref={ref}>组件A</div>
            <span>{props.desc}</span>
        </h1>
    );
}

const NewCompA = React.forwardRef(CompA);

export default class App extends Component {
    refA = React.createRef();

    componentDidMount() {
        console.log(this.refA);
    }

    render() {
        return <NewCompA ref={this.refA} desc="测试"></NewCompA>;
    }
}

打印结果

在这里插入图片描述

解释

通过 React.forwardRef() 来实现 ref 转发。其实就是通过 HOC:参数为组件,返回新组件。

特点:

  • 参数只能是函数组件,并且该函数接收2个参数
    • 参数一不变,依旧是 props
    • 参数二就是一个 ref: {current: null},也就是 React.forwardRef() 返回的新组件接收的 ref 属性。它让使用者来决定作为谁的引用。比如上面的例子中,就作为一个子元素的引用。
  • 返回的新组件,和原来的函数组件没有任何区别,只是可以传递 ref 属性了。

2,类组件如何使用

既然明确规定了 React.forwardRef() 的参数只能是函数,该函数的参数也是确定的,那可以将类组件包装一层来达到目的。

更改上面的例子如下:

class CompA extends Component {
    render() {
        return (
            <h1>
                <div ref={this.props.forwardRef}>组件A</div>
                <span>{this.props.desc}</span>
            </h1>
        );
    }
}

// forwardRef 这个属性名是随意的,只是约定俗成为这个单词了。
const NewCompA = React.forwardRef((props, ref) => {
    return <CompA {...props} forwardRef={ref}></CompA>;
});

4,应用场景-高阶组件HOC

在之前的高阶组件HOC中,有个问题没有解决:

const Alog = withLog(CompA)

此时使用的是 Alog 组件,那如何获取原组件 CompA 的方法和属性呢?
Alog 使用 ref 获取的并不是是 CompA 的组件实例。

可以使用 ref 转发解决:

源代码:

export default function withLog(Comp) {
    return class LogWrapper extends Component {
        componentDidMount() {
            console.log(`${Comp.name}组件被创建了`);
        }
        componentWillUnmount() {
            console.log(`${Comp.name}组件被销毁了`);
        }
        render() {
            return <Comp {...this.props} />;
        }
    };
}

修改后:

import React, { Component } from "react";

export default function withLog(Comp) {
    class LogWrapper extends Component {
        componentDidMount() {
            console.log(`${Comp.name}组件被创建了`);
        }
        componentWillUnmount() {
            console.log(`${Comp.name}组件被销毁了`);
        }
        render() {
            const { forwardRef, ...rest } = this.props;
            return <Comp ref={forwardRef} {...rest} />;
        }
    }
    return React.forwardRef((props, ref) => {
        return <LogWrapper {...props} forwardRef={ref}></LogWrapper>;
    });
}

这样在使用 withLog 时,并不会影响对源组件 ref 的获取。


以上。

标签:12,return,16,React,forwardRef,props,组件,ref
From: https://blog.csdn.net/qq_40147756/article/details/139076283

相关文章

  • 从CF1660F2看同余分组
    https://codeforces.com/contest/1660/problem/F2同余分组,树状数组维护逆序对先承继F1的做法,维护一个前缀和数组,让s[i]=='+'为\(1\),s[i]=='-'为\(-1\)。那么要满足两个条件:\(pre_r-pre_l\leq0\)要么加减号相同,要么减号更多(只有减号能减少)\(pre_r-pre_l......
  • AtCoder Beginner Contest 124
    A-Buttons#include<bits/stdc++.h>usingnamespacestd;intmain(){ inta,b; cin>>a>>b; intres=0; if(a>b)res+=a,a--; elseres+=b,b--; if(a>b)res+=a,a--; elseres+=b,b--; cout<<res......
  • React中何时使用memo、useCallback、useMemo以及useRef进行性能优化
    react无法做到像vue一样自动收集依赖更新(期待react19的ReactCompiler),需要开发人员手动的进行性能优化,此时memo、useCallback、useMemo、useRef就是性能优化中的重要API本文虽然介绍可应用场景,但是正常开发中,尤其是useCallback。除非遇到性能问题或者组件库封装,亦或......
  • 【CSP】202012-2 期末预测之最佳阈值
    2020年第21次CCF计算机软件能力认证  202012-2 期末预测之最佳阈值原题链接:期末预测之最佳阈值时间限制: 1.0秒空间限制: 512MiB目录题目背景题目描述输入格式输出格式样例1输入样例1输出样例1解释样例2输入样例2输出子任务解题思路AC代码期末预测之安......
  • Nginx企业级负载均衡:技术详解系列(12)—— 深入解析root、alias及location
    你好,我是赵兴晨,97年文科程序员。在生产服务器的Nginx配置中,我们总会遇到形形色色的配置方案。你是否曾注意到root和alias指令的巧妙应用?是否对那些五花八门的location匹配规则感到好奇?今天,咱们来聊聊Nginx配置中root和alias以及location的详细使用。root与aliasroot:指......
  • 12. 背包问题求具体方案
    https://www.acwing.com/problem/content/12///12.背包问题求具体方案.cpp:此文件包含"main"函数。程序执行将在此处开始并结束。//#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;/*https://www.acwing.com/problem/content......
  • create react app - cra系列比较
    省流版:craco目前还算在更新,其他的已经几年未更新了。虽然react官网已经不推荐cra了,但如果非要用这个系列还是推荐craco吧。GitHub-dilanx/craco:CreateReactAppConfigurationOverride,aneasyandcomprehensibleconfigurationlayerforCreateReactApp.3个月前Gi......
  • 持续性学习-Day16(前端基础JavaScript)
    LearnJavaScript参考教学视频:秦疆参考知识UI框架Ant-design:阿里巴巴出品,基于React的UI框架ElementUI、iview、ice:饿了吗出品,基于VUE的UI框架BootStrap:Twitter推出的一个用于前端开发的开源工具包AmazeUI:一款HTML5跨屏前端框架JavaScript构建工具Babel:JS编译......
  • React19来了,新特性
    千呼万唤的React19来了.虽然现在还是beta版本,但是不耽误大家提前准备学习下    今天medium的订阅推送了一个React19的新特性,觉得很不错,提炼点精华的说下React19是4月25号推出的beta版,从版本号大家已经可以了解到这是React的一大版本的升级.这也标志着18版本进入......
  • C129 并查集+01背包 P1455 搭配购买
    视频链接:C129并查集+01背包P1455搭配购买_哔哩哔哩_bilibili  E08【模板】背包DP01背包_哔哩哔哩_bilibiliP1455搭配购买-洛谷|计算机科学教育新生态(luogu.com.cn)//并查集+01背包#include<iostream>#include<cstring>#include<algorithm>usingname......