13_ref获取DOM和componen

该文章展示了在React中如何使用`createRef`和`forwardRef`来获取组件及DOM元素的引用,包括在不同类型的组件(类组件和函数组件)中使用的方法,并在实例中演示了通过按钮点击事件获取DOM节点的操作。
摘要由CSDN通过智能技术生成
import React, { PureComponent,createRef} from 'react'
import HelloWorld from './HelloWorld';
import GetComponent from './Fun';


export default class App extends PureComponent {
    constructor(){
        super()
        this.h2Ref = createRef()
        this.componentRef = createRef()
        this.h2elRef = null
        this.FunRef = createRef()
    }
    
    getNativeDom(){
        //第一种获取DOM的方式  在react元素上绑定ref字符串
        console.log(this.refs.why);
        // 2.提前创建好REf  保存在current里面  this.h2Ref = createRef() 最常用
        console.log(this.h2Ref.current);
        //3.利用h回调函数 拿到对应的元素,并且做一个保存
        console.log(this.h2elRef);
        //获取类组件的DOM
        console.log(this.componentRef.current);
        //获取函数组件JSX元素里面的DOM
        console.log(this.FunRef.current);
        
    }

  render() {
    return (
      <div>
        <h2 ref="why">hello world</h2>
        <h2 ref={this.h2Ref}>hello react</h2>
        <h2 ref={el=>{this.h2elRef = el}}>hello codewhy</h2>
        <HelloWorld ref={this.componentRef}/>
        <GetComponent  ref={this.FunRef}/>
        <button onClick={e=>this.getNativeDom()}>获取DOM</button>
      </div>
    )
  }
}

import { forwardRef } from "react"

const GetComponent = forwardRef(function GetComponent(props,ref){
    return(
        <div>
            <h2 ref={ref}>hello Function</h2>
            <button>按钮</button>
        </div>
    )
})


export default GetComponent

import React, { PureComponent } from 'react'

export default class HelloWorld extends PureComponent {
  render() {
    return (
      <div>HelloWorld</div>
    )
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值