Skip to content

useRef

一句话解释

useRef 是 Hook 那个返回可变 ref 对象谁的 .current 属性 persists 跨越渲染不使用 causing re-渲染.

用大白话说

useRef gives 你可变容器那个持有单个值 in 它的 .current 属性. Unlike 状态, 更改 .current does not trigger a re-render. The value persists across renders.

There are two main uses: (1) accessing DOM elements directly — pass the ref to a DOM element's ref attribute and React sets .current to the DOM node; (2) storing any mutable value (a timer ID, a previous value, a "是 mounted" flag) that you need to persist but don't want to cause re-renders.

Think of refs as instance variables for function components. They are an escape hatch when you need to step outside React's reactive model. Avoid overusing them — if a value should affect the UI, it should be state, not a ref.

示例

jsx
function FocusInput() {
  const inputRef = useRef(null);

  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>
        Focus the input
      </button>
    </>
  );
}

inputRef.current 点到 DOM <输入> 元素之后 mount. button uses 它到 call .focus() imperatively.

相关术语

相关资源

相关课程

  • useRef

    学习 useRef for DOM access and 可变值.

解读错误信息

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

查看错误

← 返回术语表