React中ref的使用

91 阅读3分钟

React不推荐直接操作原生DOM

在React的开发模式中,通常情况下不需要、也不建议直接操作DOM原生,但是某些特殊的情况,确实需要获取到DOM进行某些操作。比如说:

  • 管理焦点,文本选择或媒体播放
  • 触发强制动画
  • 集成第三方DOM库

创建refs来获取DOM

如何创建refs来获取对应的DOM呢?目前有三种方式

  • 方式一:传入字符串
    • 使用时通过 this.refs.传入的字符串格式获取对应的元素
  • 方式二:传入一个对象
    • 对象是通过 React.createRef() 方式创建出来的
    • 使用时获取到创建的对象其中有一个current属性就是对应的元素
  • 方式三:传入一个函数
    • 该函数会在DOM被挂载时进行回调,这个函数会传入一个 元素对象,我们可以自己保存
    • 使用时,直接拿到之前保存的元素对象即可

方式一(字符串方式,官方已废弃)

import React, { PureComponent } from 'react'

export default class App extends PureComponent {
  
  componentDidMount(){

  }
  render() {
    return (
      <div>
        {/* <h2 ref=字符串/对象/函数>Hello React</h2> */}
        <h2 ref= "titleRef">Hello React</h2>

        <button onClick = {e => this.changeText()}>改变文本</button>
      </div>
    )
  }
  changeText(){
    //不是$refs
    console.log(this.refs.titleRef); //这个就是DOM元素了
    this.refs.titleRef.innerHTML = 'Hello World'      
  }
}

方式二:(官方推荐,后期新增的)

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

export default class App extends PureComponent {
  constructor(props){
    super(props)
    this.titleRef = createRef()
  }
  componentDidMount(){

  }
  render() {
    return (
      <div>
        {/* <h2 ref=字符串/对象/函数>Hello React</h2> */}
        <h2 ref = {this.titleRef}>Hello React</h2>
        <button onClick = {e => this.changeText()}>改变文本</button>
      </div>
    )
  }
  changeText(){
    //使用方式二:对象的方式
    console.log(this.titleRef);
    // this.titleRef.current 就是DOM元素了,这里是h2
    this.titleRef.current.innerHTML = 'Hello World'
      
  }
}

image.png

this.titleRef image.png

方式三:(传入回调函数)

import React, { PureComponent, } from 'react'

export default class App extends PureComponent {
  constructor(props){
    super(props)

    this.titleEl = null //这里默认赋值为Null
  }
  componentDidMount(){

  }
  render() {
    return (
      <div>
        {/* <h2 ref=字符串/对象/函数>Hello React</h2> */}
           {/* 传入回调 */}
        <h2 ref={ arg => this.titleEl = arg }> Hello React</h2>
        <button onClick = {e => this.changeText()}>改变文本</button>
      </div>
    )
  }
  changeText(){
    //使用方式三:回调函数方式
    console.log(this.titleEl); //DOM元素
    this.titleEl.innerHTML = "Hello World"       
  }
}

ref的类型

ref 的值根据节点的类型而有所不同:

  • 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性;
  • 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性
  • 你不能在函数组件上使用 ref 属性,因为他们没有实例

ref在组件上,this.xxRef.current就是组件对象。

注意:函数式组件上无法使用ref属性,因为它们没有实例。

代码演示:

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

class Counter extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
  }
  render() {
    return (
      <div>
        <h2>当前计数: {this.state.counter}</h2>
        <button onClick={e => this.increment()}>+1</button>
      </div>
    )
  }

  increment() {
    this.setState({
      counter: this.state.counter + 1
    })
  }
}

export default class App extends PureComponent {

  constructor(props) {
    super(props);   
    this.counterRef = createRef()
  }

  render() {
    return (
      <div>
        <Counter ref={this.counterRef}/>
        <button onClick = { e => this.appBtnClick()}>APP按钮</button>
      </div>
    )
  }

  appBtnClick() {
    //这里current打印下来是个组件对象
    this.counterRef.current.increment(); //我们点击APP按钮,可以改变子组件的数字
  }
}

函数式组件是没有实例的,所以无法通过ref获取他们的实例:

  • 但是某些时候,我们可能想要获取函数式组件中的某个DOM元素
  • 这个时候我们可以通过 React.forwardRef ,后面我们也会学习 hooks 中如何使用ref

ref的转发

我们来演示一下使用函数式组件报的错

image.png image.png

这个ref是React内部管理的,不是我们自定义。

我们可以用自带的一个高阶函数forwardRef让函数式组件也能使用ref。

image.png

import React, { PureComponent,createRef,forwardRef } from 'react'

class Home extends PureComponent{
  render(){
    return <h2 >Home</h2>
  }
}

const Profile = forwardRef( //Profile是高阶组件的返回值
  function (props,ref){  //通过forward的Ref,间接将ref传过去了,这个就是转发
    return <h2 ref = {ref} >Profile</h2>
  }
)

export default class App extends PureComponent {
  constructor(props){
    super(props)
    this.titleRef = createRef()
    this.homeRef = createRef()
    this.profileRef = createRef() //这是不行的
  }
  render() {
    return (
      <div>
        <h2 ref = {this.titleRef}>Hello Wrold</h2>
        <Home ref = {this.homeRef} />
        <Profile ref = {this.profileRef}></Profile>
        <button onClick = {e => this.printRef()}>打印ref</button>
      </div>
    )
  }
  printRef(){
    console.log(this.titleRef.current);
    console.log(this.homeRef.current);
    console.log(this.profileRef.current);
  }
}