程序员鸡皮

文章 分类 评论
90 3 11

站点介绍

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

React中ref获取类组件实例

abzzp 2025-04-02 81 0条评论 前端 React

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

发布于2024-07-04

我们先看一下使用示例,然后再解释原理。代码如下:

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

class HelloWorld extends PureComponent{
    test(){
        console.log("test-------")
    }
    
    render(){
        return <h1>Hello World</h1>
    }
}

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

export default App

上面代码中,我们通过createRef()创建了一个ref引用对象,并将其赋值给this.hwRef。然后在HelloWorld组件上使用<HelloWorld ref={this.hwRef}></HelloWorld>将这个引用传递给子组件。 这就是直接通过ref获取子组件实例的方法。最后我们附上浏览器中运行结果:
React中ref获取类组件实例
感谢您的观看,我们下次再见!

评论(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年05月

    123
45678910
11121314151617
18192021222324
25262728293031

文章目录

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

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