Detailed explanation of cross-usage of Ref in React

Detailed explanation of cross-usage of Ref in React

1. First, let’s explain what Ref is

Ref forwarding is a technique that automatically passes a ref through a component to one of its children. This is usually not necessary for components in most applications. But it is useful for some components, especially reusable component libraries.

Ref official website description: click here

2. Usage of ref in hooks

1. Usage of ref in HTMLDom hooks

Just use it as usual on the official website. Here is an example:

const Fn = ()=>{
    const testRef = useRef(null);
    console.log('testRef',testRef.current); // Will render twice, the first time prints null, the second time is <div>test</div>
    return (
        <div ref={testRef}>test</div>
    )
}

2. Usage of ref in hooks and functional components

Here you just need to pass the ref attribute to the functional component

const Fn = ()=>{
    const testRef = useRef(null);
    // Define Test function component const Test = ({ refs }) => <div ref={refs}>I am ReactDOM test</div>;
    console.log('testRef',testRef.current); // Will render twice, the first time prints null, the second time is <div>I am ReactDOM test</div>
    return (
        {/* The reason why refs is used here instead of ref as prop is because ref will be specially processed by react and will not be passed through to react components as props, similar to key */}
         <Test refs={testRef} /> 
    )
}

3. Using ref with class components in hooks

Here you only need to manually assign the value to the useRef object in the callback ref of the class component. More callback refs: here

import ReactDom from 'react-dom';

const Fn = ()=>{
    const testClassRef = useRef(null);
    // Define the TestClass class component class TestClass extends React.Component {
        render() {
          return (
            <div >
                I am the TestClass component test</div>
          )
        }
    }
    console.log('testClassRef',testClassRef.current); // Will render twice, the first time prints null, the second time is <div>I am a TestClass component test</div>
    return (
        {/* The reason why refs is used here instead of ref as prop is because ref will be specially processed by react and will not be passed through to react components as props, similar to key */}
         <TestClass 
             ref={el => {
                console.log('new render refs')
                testClassRef.current = ReactDom.findDOMNode(el);
             }} 
         /> 
    )
}

4. Using ref with class and react-redux in hooks

When you encounter a class component wrapped by connect, because the outermost layer has been wrapped into a react-redux Provider, you need to pass the ref attribute through to the real React component. At this time, you need to pay attention to the forwardRef attribute of connect.

import ReactDom from 'react-dom';
import { connect } from 'react-redux';

const Fn = ()=>{
    const testClassRef = useRef(null);
    // Define the TestClass class component class TestClass extends React.Component {
        render() {
          return (
            <div >
                I am the TestClass component test</div>
          )
        }
    }
    //Define the component wrapped by connect of TestClass //forwardRef:true Set redux to allow ref to be passed as props to the component wrapped by connect const TestClassConnect = connect(null, null, null, { forwardRef: true })(TestClass);
    
    console.log('testClassRef',testClassRef.current); // Will render twice, the first time prints null, the second time is <div>I am a TestClass component test</div>
    return (
        {/* The reason why refs is used here instead of ref as prop is because ref will be specially processed by react and will not be passed through to react components as props, similar to key */}
         <TestClassConnect
            ref={el => {
              console.log('new render refs')
              testClassRef.current = ReactDom.findDOMNode(el);
            }}
          />
    )
}

The above is a detailed explanation of the cross-usage of Ref in React. For more information about the cross-usage of Ref in React, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to use React forwardRef and what to note
  • The complete usage of setup, ref, and reactive in Vue3 combination API
  • How to deeply understand React's ref attribute
  • Detailed explanation of the use of Refs in React's three major attributes
  • Specific use of useRef in React
  • React ref usage examples
  • Detailed explanation of how to use Ref in React
  • Detailed explanation of the use of react-refetch
  • Learn two demo examples of ref in React
  • Tutorial on using refs in React
  • Detailed explanation of the use of React component refs
  • RefreshContorl pull-down refresh usage in React Native

<<:  How to install and configure ftp server in CentOS8.0

>>:  Get the IP and host name of all hosts on Zabbix

Recommend

Six ways to reduce the size of Docker images

Since I started working on Vulhub in 2017, I have...

5 JavaScript Ways to Flatten Arrays

Table of contents 1. Concept of array flattening ...

Summary of Docker common commands and tips

Installation Script Ubuntu / CentOS There seems t...

Research on the value of position attribute in CSS (summary)

The CSS position attribute specifies the element&...

WeChat applet records user movement trajectory

Table of contents Add Configuration json configur...

A mobile adaptive web page effect solves the problem of small display page

For work needs, I need to make a mobile phone adap...

Steps to set up HTTPS website based on Nginx

Table of contents Preface: Encryption algorithm: ...

JavaScript to implement login slider verification

This article example shares the specific code of ...

How to implement form validation in Vue

1. Installation and use First, install it in your...

HTML+CSS+JS to implement the Don't Step on the Whiteboard game

Table of contents Background 1. Thought Analysis ...

The process of deploying a project to another host using Jenkins

environment Hostname ip address Serve Jenkins 192...

How to view Docker container application logs

docker attach command docker attach [options] 容器w...

Correct modification steps for Docker's default network segment

background A colleague is working on his security...

Teach you how to use AWS server resources for free

AWS - Amazon's cloud computing service platfo...

js realizes the magnifying glass effect of shopping website products

This article shares the specific code of js to ac...