ref的使用

文章目录

    • ref的作用
    • 如何使用
      • 传入字符串
      • 传入一个对象
      • 传入一个函数
      • 举例
    • ref 的节点类型
    • ref 的转发
      • forwardRef方法

ref的作用

react 中,很少直接的操作dom 元素,如果需要操作 dom 元素的话,那么就需要使用到 ref

常见的应用场景

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

如何使用

传入字符串

使用时通过 this.refs.传入的字符串格式获取对应的元素

传入一个对象

  • 对象是通过 React.createRef() 方式创建出来的
  • 使用时获取到创建的对象其中有一个current属性就是对应的元素

传入一个函数

  • 该函数会在DOM被挂载时进行回调,这个函数会传入一个元素对象,可以自己保存;
  • 使用时,直接拿到之前保存的元素对象

举例

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

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

    this.titleRef = createRef();
    this.titleEl = null;
  }

  render() {
    return (
      <div>
        <h2 ref="title">传入一个字符串</h2>
        <h2 ref={this.titleRef}>传入一个对象</h2>
        <h2 ref={element => this.titleEl = element}>传入一个函数</h2>

        <button onClick={e => this.changeText()}>改变文本</button>
      </div>
    )
  }

  changeText() {
    this.refs.title.innerHTML = "小冯";
    this.titleRef.current.innerHTML = "小冯";
    this.titleEl.innerHTML = "小冯";
  }
}

ref 的节点类型

  • 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性
  • 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性
  • 另外在函数组件上不能使用 ref 属性,因为没有实例
import React, { PureComponent, createRef } 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.increment()}>app +1</button>
      </div>
    )
  }

  increment() {
    console.log(this.counterRef.current);
    this.counterRef.current.increment();
  }
}

ref 的转发

ref 转发允许某些组件接收 ref,并将其向下传递(或者是转发它)给子组件

官网

forwardRef方法

参数:传递的是函数组件,不能是类组件,并且,函数组件需要有第二个参数来得到ref

const Profile = forwardRef(function(props, ref) {
  return <p ref={ref}>Profile</p>
})

返回值:一个新的组件

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

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

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

    this.homeTitleRef = createRef();
  }

  render() {
    return (
      <div>
        <Home ref={this.homeTitleRef}/>
        <button onClick={e => this.printInfo()}>打印ref</button>
      </div>
    )
  }

  printInfo() {
    console.log(this.homeTitleRef.current);
  }
}

你可能感兴趣的:(react,react,ref的使用,ref,的节点类型,ref的转发)