search
HomeWeb Front-endJS TutorialLet you understand Ref in React and share knowledge points worth knowing.

This article will take you to understand Ref in React and introduce some knowledge points you need to know about Ref. I hope it will be helpful to everyone!

Let you understand Ref in React and share knowledge points worth knowing.

Intro

In React projects, there are many scenarios where Ref is needed. For example, use the ref attribute to obtain the DOM node and obtain the ClassComponent object instance; use the useRef Hook to create a Ref object to solve problems such as setInterval not being able to obtain the latest state. Question; you can also call the React.createRef method to manually create a Ref object. [Related recommendations: Redis Video Tutorial]

Although Ref is very simple to use, it is inevitable to encounter problems in actual projects. This article will From the perspective of source code, sort out various issues related to Ref, and clarify what is done behind the APIs related to ref. After reading this article, you may have a deeper understanding of Ref.

First of all ref is the abbreviation of reference, which is a reference. In the type declaration file of react, you can find several types related to Ref, and they are listed here.

RefObject/MutableRefObject

interface RefObject<T> { readonly current: T | null; }
interface MutableRefObject<T> { current: T; }

When using useRef Hook returns RefObject/MutableRefObejct. Both types define a { current: T } object structure, the difference is that the current property of RefObject is read-only. If refObject.current is modified, Typescript will warn⚠️.

const ref = useRef<string>(null)
ref.current = &#39;&#39; // Error

TS Error: Cannot assign to "current" because it is a read-only property.

Let you understand Ref in React and share knowledge points worth knowing.

View the definition of the useRef method. Function overloading is used here. When passing in generic parameters T will return RefObject<t></t> when it does not contain null, and MutableRefObject<t>## when it contains </t>null. #.

function useRef<T>(initialValue: T): MutableRefObject<T>;
function useRef<T>(initialValue: T | null): RefObject<T>;

So if you want the current property of the created ref object to be modifiable, you need to add

| null.

const ref = useRef<string | null>(null)
ref.current = &#39;&#39; // OK

When calling the

React.createRef() method, it also returns a RefObject.

createRef

export function createRef(): RefObject {
  const refObject = {
    current: null,
  };
  if (__DEV__) {
    Object.seal(refObject);
  }
  return refObject;
}

RefObject/MutableRefObject was added in version 16.3, if you use an earlier version , need to use Ref Callback.

RefCallback

Using

Ref Callback is to pass a callback function. When react calls back, the corresponding instance will be passed back. You can save it yourself for convenience. transfer. The type of this callback function is RefCallback.

type RefCallback<T> = (instance: T | null) => void;

Using

RefCallback Example:

import React from &#39;react&#39;

export class CustomTextInput extends React.Component {
  textInput: HTMLInputElement | null = null;

  saveInputRef = (element: HTMLInputElement | null) => {
    this.textInput = element;
  }

  render() {
    return (
      <input type="text" ref={this.saveInputRef} />
    );
  }
}

Ref/LegacyRef

In the type declaration, there is also the Ref/LegacyRef type , they are used to refer to Ref types generally.

LegacyRef is a compatible version. In the previous old version, ref can also be string.

type Ref<T> = RefCallback<T> | RefObject<T> | null;
type LegacyRef<T> = string | Ref<T>;

Only when you understand the types related to Ref can you become more comfortable writing Typescript.

Passing of Ref

Special props

When using

ref on a JSX component, we pass ## The #ref attribute sets a Ref. We all know that the syntax of jsx will be compiled into the form of createElement by tools such as Babel. <pre class='brush:php;toolbar:false;'>// jsx &lt;App ref={ref} id=&quot;my-app&quot; &gt;&lt;/App&gt; // compiled to React.createElement(App, { ref: ref, id: &quot;my-app&quot; });</pre>It seems that

ref

is no different from other props, but if you try to print props.ref inside the component, it is undefined. And the dev environment console will give a prompt.

Trying to access it will result in
undefined

being returned. If you need to access the same value within the child component, you should pass it as a different prop.

React 对 ref 做了啥?在 ReactElement 源码中可以看到,refRESERVED_PROPS,同样有这种待遇的还有 key,它们都会被特殊处理,从 props 中提取出来传递给 Element

const RESERVED_PROPS = {
  key: true,
  ref: true,
  __self: true,
  __source: true,
};

所以 ref 是会被特殊处理的 “props“

forwardRef

16.8.0 版本之前,Function Component 是无状态的,只会根据传入的 props render。有了 Hook 之后不仅可以有内部状态,还可以暴露方法供外部调用(需要借助 forwardRefuseImperativeHandle)。

如果直接对一个 Function Componentref,dev 环境下控制台会告警,提示你需要用 forwardRef 进行包裹起来。

function Input () {
    return <input />
}

const ref = useRef()
<Input ref={ref} />

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

forwardRef 为何物?查看源码 ReactForwardRef.js__DEV__ 相关的代码折叠起来,它只是一个无比简单的高阶组件。接收一个 render 的 FunctionComponent,将它包裹一下定义 $$typeofREACT_FORWARD_REF_TYPEreturn 回去。

Let you understand Ref in React and share knowledge points worth knowing.

跟踪代码,找到 resolveLazyComponentTag,在这里 $$typeof 会被解析成对应的 WorkTag。

Let you understand Ref in React and share knowledge points worth knowing.

REACT_FORWARD_REF_TYPE 对应的 WorkTag 是 ForwardRef。紧接着 ForwardRef 又会进入 updateForwardRef 的逻辑。

case ForwardRef: {
  child = updateForwardRef(
    null,
    workInProgress,
    Component,
    resolvedProps,
    renderLanes,
  );
  return child;
}

这个方法又会调用 renderWithHooks 方法,并在第五个参数传入 ref

nextChildren = renderWithHooks(
  current,
  workInProgress,
  render,
  nextProps,
  ref, // 这里
  renderLanes,
);

继续跟踪代码,进入 renderWithHooks 方法,可以看到,ref 会作为 Component 的第二个参数传递。到这里我们可以理解被 forwardRef 包裹的 FuncitonComponent 第二个参数 ref 是从哪里来的(对比 ClassComponent contructor 第二个参数是 Context)。

Let you understand Ref in React and share knowledge points worth knowing.

了解如何传递 ref,那下一个问题就是 ref 是如何被赋值的。

ref 的赋值

打断点(给 ref 赋值一个 RefCallback,在 callback 里面打断点) 跟踪到代码 commitAttachRef,在这个方法里面,会判断 Fiber 节点的 ref 是 function 还是 RefObject,依据类型处理 instance。如果这个 Fiber 节点是 HostComponent (tag = 5) 也就是 DOM 节点,instance 就是该 DOM 节点;而如果该 Fiber 节点是 ClassComponent (tag = 1),instance 就是该对象实例。

function commitAttachRef(finishedWork) {
  var ref = finishedWork.ref;

  if (ref !== null) {
    var instanceToUse = finishedWork.stateNode;

    if (typeof ref === &#39;function&#39;) {
      ref(instanceToUse);
    } else {
      ref.current = instanceToUse;
    }
  }
}

以上是 HostComponent 和 ClassComponent 中对 ref 的赋值逻辑,对于 ForwardRef 类型的组件走的是另外的代码,但行为基本是一致的,可以看这里 imperativeHandleEffect

接下里,我们继续挖掘 React 源码,看看 useRef 是如何实现的。

useRef 的内部实现

通过跟踪代码,定位到 useRef 运行时的代码 ReactFiberHooks

Let you understand Ref in React and share knowledge points worth knowing.

这里有两个方法,mountRefupdateRef,顾名思义就是对应 Fiber 节点 mountupdate 时对 ref 的操作。

function updateRef<T>(initialValue: T): {|current: T|} {
  const hook = updateWorkInProgressHook();
  return hook.memoizedState;
}

function mountRef<T>(initialValue: T): {|current: T|} {
  const hook = mountWorkInProgressHook();
  const ref = {current: initialValue};
  hook.memoizedState = ref;
  return ref;
}

可以看到 mount 时,useRef 创建了一个 RefObject,并将它赋值给 hookmemoizedStateupdate 时直接将它取出返回。

不同的 Hook memoizedState 保存的内容不一样,useState 中保存 state 信息, useEffect 中 保存着 effect 对象,useRef 中保存的是 ref 对象...

mountWorkInProgressHookupdateWorkInProgressHook 方法背后是一条 Hooks 的链表,在不修改链表的情况下,每次 render useRef 都能取回同一个 memoizedState 对象,就这么简单。

应用:合并 ref

至此,我们了解了在 React 中 ref 的传递和赋值逻辑,以及 useRef 相关的源码。用一个应用题来巩固以上知识点:有一个 Input 组件,在组件内部需要通过 innerRef HTMLInputElement 来访问 DOM 节点,同时也允许组件外部 ref 该节点,需要怎么实现?

const Input = forwardRef((props, ref) => {
  const innerRef = useRef<HTMLInputElement>(null)
  return (
    <input {...props} ref={???} />
  )
})

考虑一下上面代码中的 ??? 应该怎么写。

============ 答案分割线 ==============

通过了解 Ref 相关的内部实现,很明显我们这里可以创建一个 RefCallback,在里面对多个 ref 进行赋值就可以了。

export function combineRefs<T = any>(
  refs: Array<MutableRefObject<T | null> | RefCallback<T>>
): React.RefCallback<T> {
  return value => {
    refs.forEach(ref => {
      if (typeof ref === &#39;function&#39;) {
        ref(value);
      } else if (ref !== null) {
        ref.current = value;
      }
    });
  };
}

const Input = forwardRef((props, ref) => {
  const innerRef = useRef<HTMLInputElement>(null)
  return (
    <input {...props} ref={combineRefs(ref, innerRef)} />
  )
})

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Let you understand Ref in React and share knowledge points worth knowing.. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment