Skip to content

useRef

介绍

在 React 组件中获取/操作 DOM,需要使用 useRef 函数。

提示

类似于 vue 中的 ref 模板引用。

快速入门

语法

ts
const refContainer = useRef<T>(initialValue: T)

示例

tsx
import { useRef } from 'react'

function Refs() {
  const input = useRef<HTMLInputElement>(null)

  const handleClick = () => {
    console.log(input)
    input.current?.focus()
  }

  return (
    <>
      <input ref={input} />
      <button type="button" onClick={handleClick}>
        聚焦
      </button>
    </>
  )
}

export default Refs

useRef 的核心特性

更新 useRef 的值不会触发组件的重新渲染。

useRef 的应用场景

1. 访问和操作 DOM 元素

常见需求:

  1. 自动聚焦 input
  2. 获取元素的尺寸和位置
  3. 控制视频、音频的播放
  4. 集成第三方 DOM 库(如:d3.js)

2. 存储跨渲染周期的可变值

经典场景:管理定时器

jsx
function Stopwatch() {
  // 使用 ref 存储定时器 ID
  const intervalRef = useRef(null)
  const [seconds, setSeconds] = useState(0)

  const handleStart = () => {
    // 防止重复启动
    if (intervalRef.current !== null) return

    intervalRef.current = setInterval(() => {
      // 使用函数式更新,确保获取最新的 state
      setSeconds((s) => s + 1)
    }, 1000)
  }

  const handleStop = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current)
      intervalRef.current = null // 清理 ref
    }
  }

  const handleReset = () => {
    handleStop()
    setSeconds(0)
  }

  return (...)
}

为什么不用 useState?

如果定时器 ID 存储到 useState 中,每次 setTimerId 都会触发组件重新渲染,导致不必要的性能开销。

基于 MIT 许可发布