Summary of some common uses of refs in React

Summary of some common uses of refs in React

What are Refs

Refs provide a way to allow us to access DOM nodes or React elements created in the render method.
Ref forwarding is a technique that automatically passes refs through components to their children. Tools commonly used to obtain DOM nodes or React element instances. Refs in React provide a way to allow users to access DOM nodes or React elements created in the render method.

Refs

Ref forwarding is an optional feature that allows certain components to receive a ref and pass it down (in other words, "forward" it) to child components.

By default, you cannot use the ref attribute on function components because they don't have instances:

1. String Refs

It is not recommended to use this method because of some issues with string refs. It is deprecated and may be removed in a future version.

import React from "react";
// Parent component export default class StringRef extends React.PureComponent {
  componentDidMount() {
    console.log("stringRefDom:", this.refs.stringRefDom);
    console.log("stringRefComp:", this.refs.stringRefComp);
  }
  render() {
    return (
      <div>
        {/*How to use native components*/}
        <div ref={"stringRefDom"}>stringRefDom</div>
        {/*How to use the class component*/}
        <StringRefComp ref={"stringRefComp"} />
      </div>
    );
  }
}
//Class component class StringRefComp extends React.PureComponent {
  render() {
    return <div>StringRefComp</div>;
  }
}

2. Callback Refs

  • If the ref callback function is defined as an inline function, it will be executed twice during the update process.
  • The first time the parameter is null, the second time the parameter DOM element is passed
  • This is because a new instance of the function is created on each render, so React clears the old ref and sets the new one.
  • The above problem can be avoided by defining the callback function of ref as a bound function of the class.
  • But most of the time it's irrelevant
import React from "react";
// Parent component export default class CallbackRef extends React.PureComponent {
  constructor(props) {
    super(props);
    this.callbackRefDom = null;
    this.callbackRefComp = null;
  }
  componentDidMount() {
    console.log("callbackRefDom:", this.callbackRefDom);
    console.log("callbackRefComp:", this.callbackRefComp);
  }
  //Callback function setCallbackRefDom = (ref) => {
    this.callbackRefDom = ref;
  };
  setCallbackRefComp = (ref) => {
    this.callbackRefComp = ref;
  };
  //Callback function render() {
    return (
      <div>
        <div ref={this.setCallbackRefDom}>callbackRefDom</div>
        <CallbackRefComp ref={this.setCallbackRefComp} />
      </div>
    );
  }
}

//Class component class CallbackRefComp extends React.PureComponent {
  render() {
    return <div>callbackRefComp</div>;
  }
}

React.createRef()

  • React 16.3 introduced
  • In earlier versions of React, callback refs are recommended.
import React from "react";
// Parent component export default class CreateRef extends React.PureComponent {
  constructor(props) {
    super(props);
    this.createRefDom = React.createRef();
    this.createRefComp = React.createRef();
  }
  componentDidMount() {
    console.log("createRefDom:", this.createRefDom.current);
    console.log("createRefComp:", this.createRefComp.current);
  }
  render() {
    return (
      <div>
        <div ref={this.createRefDom}>createRefDom</div>
        <CreateRefComp ref={this.createRefComp} />
      </div>
    );
  }
}
//Class component class CreateRefComp extends React.PureComponent {
  render() {
    return <div>CreateRefComp</div>;
  }
}

4. useRef

  • Hooks are a new feature in React 16.8
import React, { useEffect } from "react";
// Parent component const UseRef = React.memo(() => {
  // // You can also use // const createRefDom = React.createRef();
  // const createRefComp = React.createRef();
  const createRefDom = React.useRef();
  const createRefComp = React.useRef();
  useEffect(() => {
    console.log("useRefDom:", createRefDom.current);
    console.log("useRefComp:", createRefComp.current);
  }, []);
  return (
    <div>
      <div ref={createRefDom}>useRefDom</div>
      <UseRefComp ref={createRefComp} />
    </div>
  );
});

export default UseRef;

//Class component class UseRefComp extends React.PureComponent {
  render() {
    return <div>useRefComp</div>;
  }
}

5. Refs and Function Components

  • By default, you cannot use the ref attribute on function components because they don’t have instances.
  • If you want to use ref in a function component, you can use forwardRef (can be used in conjunction with useImperativeHandle)
  • Or convert the component into a class component.
import React, { useEffect, useImperativeHandle } from "react";

// Parent component const ForwardRef = React.memo(() => {
  const createRefComp = React.useRef();
  const createRefCompMethod = React.useRef();

  useEffect(() => {
    console.log("useRefComp:", createRefComp.current);
    console.log("createRefCompMethod:", createRefCompMethod.current);
    createRefComp.current.reload();
  }, []);
  return (
    <div>
      <ForwardRefFunc ref={createRefComp} />
    </div>
  );
});

export default ForwardRef;

const RefFunc = React.forwardRef((props, ref) => {
  const [name, setName] = React.useState(null);
  const reload = () => {
    console.log("reload");
    setTimeout(() => {
      setName("ForwardRefFunc");
    }, 3000);
  };
  //useImperativeHandle allows you to customize the instance value exposed to the parent component when using refuseImperativeHandle(ref, () => {
    return {
      reload: reload,
    };
  });
  return <div ref={ref}>ForwardRefFunc {name}</div>;
});
const ForwardRefFunc = React.memo(RefFunc);

The ultimate goal of forwardRef and useImperativeHandle is to try to provide a callable object to ref!

  • Refs and the DOM
  • forwardRef
  • UseImperativeHandle

Summarize

This concludes this article about some common uses of refs in React. For more information about the use of refs in React, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the use of Refs in React's three major attributes
  • An in-depth introduction to React refs
  • Tutorial on using refs in React
  • Detailed explanation of the use of React component refs
  • Do you know the Refs attribute in React?

<<:  How to expand the disk size of a virtual machine

>>:  MySQL 8.0 DDL atomicity feature and implementation principle

Recommend

Ubuntu MySQL version upgraded to 5.7

A few days ago, the library said that the server ...

Multi-service image packaging operation of Dockerfile under supervisor

Writing a Dockerfile Configure yum source cd /tmp...

MySQL 8.0.12 Installation and Usage Tutorial

Recorded the installation and use tutorial of MyS...

Share the 15 best HTML/CSS design and development frameworks

Professional web design is complex and time-consu...

Mysql solves the database N+1 query problem

Introduction In orm frameworks, such as hibernate...

Two solutions for Vue package upload server refresh 404 problem

1: nginx server solution, modify the .conf config...

CSS--overflow:hidden in project examples

Here are some examples of how I use this property ...

Summary of the benefits of deploying MySQL delayed slaves

Preface The master-slave replication relationship...

(MariaDB) Comprehensive explanation of MySQL data types and storage mechanisms

1.1 Data Type Overview The data type is a field c...

How to use not in to optimize MySql

Recently, when using select query in a project, I...

Detailed process of upgrading gcc (version 10.2.0) under CentOS7 environment

Table of contents Short Introduction 1. Check the...

Detailed Introduction to Nginx Installation and Configuration Rules

Table of contents 1. Installation and operation o...

A detailed introduction to the basics of Linux scripting

Table of contents 1. Script vim environment 2. Ho...

Detailed explanation of linux nslookup command usage

[Who is nslookup?] 】 The nslookup command is a ve...