React Hooks(四) useRef

an introduction

useRef is a function that returns a mutable reference object. The initial value of the current property of the object is the initialValue passed in, and the returned object persists throughout the life cycle of the component.

1. Usage

  • References to DOM elements are done through the ref attribute
  • Initial assignment via useRef()
  • View the value through the current attribute
import {
    
    useRef} from 'react';
const ref = useRef(initialValue);

···
//可以在组件生命周期的任何时间log该属性以查看其值
console.log(ref.current)
···

return(
    <button ref={
    
    btnRef}>
      点击
    </button>
);

2. Two key points about the current attribute

  • This property is mutable
  • Can be changed at any time during the component lifecycle

Two applications

In general, useRef has two purposes:

  • Access DOM nodes, or React elements
  • keep mutable variables

1. Access DOM nodes, or React elements

A simple case, by clicking the button to realize the input to automatically get the focus
of the class component:

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

export default class Demo extends Component {
    
    
  textInput = createRef()

  focusTextInput = () => {
    
    
    if (this.textInput.current) {
    
    
      this.textInput.current.focus();
    }
  }

  render() {
    
    
    return (
      <>
        <input type="text" ref={
    
    this.textInput} />
        <button onClick={
    
    this.focusTextInput}>点击我让input组件获得焦点</button>
      </>
    );
  }

How to write functional components:

import React, {
    
    useRef} from "react";

export default function Demo() {
    
    
  const inputRef = useRef(null);

  const focusTextInput = () => {
    
    
    if (inputRef.current) {
    
    
      inputRef.current.focus();
    }
  }

  return (
    <>
      <input type="text" ref={
    
    inputRef} />
      <button onClick={
    
    focusTextInput}>点击我让input组件获得焦点</button>
    </>
  );
}

Pay attention to the way of generating ref in two ways of writing

2. Keep mutable variables

In function components, each re-render means that the function is re-executed. If you want to keep variable references inside the function, you can use useRef.
A common scenario is the clearing of timers. We need to ensure the reference of the execution result timer of setInterval in order to accurately clear the corresponding timer.

import React, {
    
     useRef, useEffect } from 'react';

export default function Timer() {
    
    
  const timerRef = useRef();

  useEffect(() => {
    
    
    timerRef.current = setInterval(() => {
    
    
      console.log('do something');
    }, 1000);

    // 组件卸载时,清除定时器
    return () => {
    
    
      timerRef.current && clearInterval(timerRef.current);
    }
  }, []);

  return (
    <div>
      // ...
    </div>
  )
}

It must be noted that if a state or data will affect the rendering result of the DOM, it is necessary to avoid using useRef to keep the reference.

Three summary useRef

useRef does not notify you when the content of the ref object changes. Changing the current property will not cause the component to re-render.
Several main application scenarios:

  • Micromanage input with focus, blur, disable and other form management related properties
  • To add or remove classes from elements, possibly to control transitions or keyframe animations
  • Interact with other html5 libraries. Such libraries cannot be accessed through react state, and Refs provide us with a fallback.

Guess you like

Origin blog.csdn.net/LittleMoon_lyy/article/details/124521310