react——ref获取原生DOM元素

本文介绍了React中ref的应用,包括如何在HTML标签元素中使用ref以获取DOM元素,以及在组件上使用ref来调用子组件的方法。特别强调了函数式组件中无法直接通过ref获取组件对象,但可以通过React.forwardRef和hooks解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.  ref 用于HTML标签元素中

      <h2 ref=字符串/对象/函数>h2元素<h2>

其中,字符串形式 官方已不再推荐使用

1.对象形式

import React, { Component,createRef } from 'react'

export default class App extends Component {
    constructor(){
        super();
        this.titleRef=createRef();
    }
    render() {
        return (
            <div>
                <h2 ref={this.titleRef}>App组件内容</h2>
                <button onClick={e=>this.btnApp()}>App按钮</button>
            </div>
        )
    }
    btnApp(){
        this.titleRef.current.innerHTML="改变后的文本"
    }
}

2.函数形式

import React, { Component} from 'react'

export default class App extends Component {
    constructor(){
        super();
        this.titleEL=null;
    }
    render() {
        return (
            <div>
                <h2 ref={(arg)=>this.titleEL=arg}>App组件内容</h2>
                <button onClick={e=>this.btnApp()}>App按钮</button>
            </div>
        )
    }
    btnApp(){
        this.titleEL.innerHTML="11111111"
    }
}

二. ref 用于组件上

可以实现:点击父组件中的按钮,调用子组件中的方法

父组件:

import React, { Component, createRef} from 'react'
import Counter from './Counter'

export default class App extends Component {
    constructor(){
        super();
        this.counterRef=createRef()
    }
    render() {
        return (
            <div>
                <Counter ref={this.counterRef}/>
                <button onClick={e=>this.CounterClick()}>App按钮</button>
            </div>
        )
    }
    CounterClick(){
        this.counterRef.current.CounterClick()
    }
}

子组件:

import React, { PureComponent } from 'react'

export default class Counter extends PureComponent {
    constructor(){
        super();
        this.state={
            num:0
        }
    }
    render() {
        return (
            <div>
                num:{this.state.num}
                <button onClick={e=>this.CounterClick()}>Counter+1</button>
            </div>
        )
    }
    CounterClick(){
        this.setState({
            num:this.state.num+1
        })
    }
}

注意:当ref用于组件时,current才表示组件对象

若子组件是函数式组件,则无法获取对应的组件对象,因为函数式组件没有实例。函数式组件中不能使用ref获取。要想获取函数式组件的DOM元素,要用React.forwardRef(高阶组件)以及hooks

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值