程序员鸡皮

文章 分类 评论
90 3 11

站点介绍

一名PHP全栈程序员的日常......

React中ref获取函数组件的DOM

abzzp 2025-04-03 67 0条评论 前端 React

首页 / 正文
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......

发布于2024-07-04

之前我们已经讲过了如何获取类组件实例,那么如何获取函数组件的DOM呢?

原理

我们可以通过forwardRef将函数组件转化为类组件,然后通过createRef创建ref引用对象,最后将ref引用对象传递给函数组件。

案例代码

import React,{PureComponent,createRef,forwardRef} from "react";

const HelloWorld = forwardRef(function(props,ref){
    return (
        <div>
            <h1 ref={ref}>Hello World</h1>
            <p>哈哈哈</p>
        </div>
    )
})

export class App extends PureComponent{
    constructor(){
        super()
        this.hwRef = createRef()
    }
    
    getComponent(){
        console.log(this.hwRef.current)
    }
    
    render(){
        return (
            <div>
                <HelloWorld ref={this.hwRef}></HelloWorld>
                <button onClick={e=>this.getComponent()}>获取组件实例</button>
            </div>
        )
    }
}

export default App

注意事项

  • 函数组件必须使用forwardRef进行转化
  • 函数组件必须使用ref接收ref引用对象
  • 函数组件必须使用current获取DOM

最后,我们来看一下运行结果:

React中ref获取函数组件的DOM

感谢您的观看,我们下次再见!

评论(0)

最新评论

  • See details

    of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.

  • 晚夜

    新年快乐!

  • abzzp

    十天看一部剧,还可以吧[[呲牙]]

  • ab

    @梦不见的梦 行,谢谢提醒,我优化一下

  • 梦不见的梦

    网站的速度有待提升,每次打开都要转半天还进不来呢

  • abzzp

    @React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?[[微笑]]

  • abzzp

    @Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品[[发呆]]

  • Teacher Du

    我们大学那会,献血还给学分~

  • @ab 我想去学网安,比如网警,但分也贼高😕

  • ab

    @夜 加油,你一样也可以成为程序员的,需要学习资料可以V我

日历

2025年04月

  12345
6789101112
13141516171819
20212223242526
27282930   

文章目录

推荐关键字: React vue JavaScript Golang 观后感 ES6 SEO 读后感

站点公告
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......
点击小铃铛关闭
配色方案