如何正确在 React 中动态创建多个 useRef 实例以实现滚动定位功能

react 的 `useref` 必须在组

件或自定义 hook 的顶层调用,不能在循环、条件语句或回调中使用;本文将展示如何通过单个 `useref` 管理多个 dom 元素引用,并安全实现基于标签的滚动跳转。

该错误的根本原因在于违反了 React Hooks 的核心规则:Hooks 必须始终在顶层调用,且调用顺序必须稳定。你在 useDivRefs 中对 labels.forEach 内部调用 useRef(null),相当于在每次迭代中“动态”调用 Hook —— 这不仅破坏了调用顺序的可预测性,也使 React 无法正确关联 ref 与组件渲染周期,因此触发 react-hooks/rules-of-hooks ESLint 报错。

✅ 正确做法是:用一个 useRef 存储数组(或对象),并在 ref 回调函数中动态赋值。这种方式既符合 Hook 规则,又能灵活映射任意数量的 DOM 节点。

以下是推荐的完整实现方案:

import { useRef, useEffect } from 'react';

// ✅ 安全的自定义 Hook:返回带 ref 映射能力的对象
const useDivRefs = (labels) => {
  const refs = useRef({});

  // 初始化 refs 对象(仅在首次渲染时设置 key,避免重复覆盖)
  useEffect(() => {
    labels.forEach((label) => {
      const targetId = label.replace(/\s+/g, '');
      if (!(targetId in refs.current)) {
        refs.current[targetId] = null;
      }
    });
  }, [labels]);

  return refs;
};

const MyComponent = () => {
  const labels = ['div 1', 'div 2', 'div 3'];

  // 使用自定义 Hook 获取统一 ref 容器
  const divRefs = useDivRefs(labels);

  // 滚动到指定标签区域的辅助函数
  const scrollToSection = (label) => {
    const targetId = label.replace(/\s+/g, '');
    const el = divRefs.current[targetId];
    if (el) {
      el.scrollIntoView({ behavior: 'smooth' });
    }
  };

  return (
    
      {/* 导航栏 */}
      

      {/* 可滚动内容区 */}
      
{labels.map((label, i) => { const targetId = label.replace(/\s+/g, ''); return (
{ if (el) divRefs.current[targetId] = el; }} style={{ minHeight: '100vh', padding: '40px 20px', backgroundColor: i % 2 === 0 ? '#f9f9f9' : '#fff', }} >

{label}

This is section {i + 1}. Scroll down to see more.

); })}
); }; export default MyComponent;

? 关键要点说明:

  • useRef({}) 创建一个持久化的可变对象容器,其 .current 属性可随时写入任意键值(如 refs.current['div1'] = domNode);
  • 使用 ref 回调函数(ref={(el) => {...}})而非 useRef() 多次调用,确保每个元素挂载/卸载时精准更新引用;
  • useEffect 用于初始化 refs.current 的键结构(可选,提升代码健壮性);
  • 支持 id 属性 + scrollIntoView 组合,兼顾语义化 HTML 和无障碍访问(a11y)。

⚠️ 注意事项:

  • 不要直接在 ref 回调中调用 setState(如 setX(...)),否则可能引发无限循环;
  • 若需在 useEffect 中读取这些 ref,请添加依赖项 divRefs 并使用 divRefs.current 访问;
  • 避免在服务端渲染(SSR)环境中依赖 ref.current 值(此时为 null),应配合 useEffect 或 if (typeof window !== 'undefined') 判断。

通过这种模式,你既能优雅管理动态数量的 DOM 引用,又完全遵守 React 的 Hook 规范,为后续实现平滑滚动、动画联动或焦点控制打下坚实基础。