Skip to content

Ref

一句话解释

ref 是对象使用 .current 属性那个持有引用到 DOM 元素 or 可变值 那个 persists 跨越渲染.

用大白话说

A ref (reference) is an escape hatch from React's declarative model. It gives you direct access to a DOM element or a mutable value that doesn't trigger re-renders.

You create a ref with useRef(initialValue) and attach it to a DOM element via the ref attribute: <输入 ref={myRef} />. After mount, myRef.current points to the actual DOM node, and you can call imperative methods like .focus(), .scrollIntoView(), or .值.

Refs are also used to store any mutable value that should persist across renders but shouldn't cause a re-render when changed — a timer ID, a previous prop value, or a "有 mounted" flag. Think of refs as instance variables for function components.

示例

jsx
const timerRef = useRef(null);

timerRef.current = setInterval(() => {
  console.log("tick");
}, 1000);

// Later: clearInterval(timerRef.current);

ref 存储 timer ID 那个 persists 跨越渲染. 更改 .current doesn't 触发 re-渲染.

相关术语

相关资源

相关课程

  • useRef

    学习 refs for DOM access and 可变 storage.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表