本文讲解如何规避“react hook 'useref' cannot be called inside a callback”错误,通过 `useref` 持有引用数组并结合回调 ref 实现动态 dom 元素引用管理,适用于滚动定位、焦点控制等场景。
在 React 中,Hooks 的调用必须严格遵守规则:只能在函数组件的顶层或自定义 Hook 的顶层调用,不能在循环、条件语句或回调函数中调用(如 forEach、map 内部)。你原代码中在 labels.forEach(...) 回调里调用 useRef(null),直接违反了这一规则

✅ 正确做法是:用一个 useRef 容器(如数组)统一管理多个 DOM 引用,并通过回调 ref(callback ref)动态赋值。这种方式既符合 Hooks 规则,又能灵活支持动态数量的元素。
import { useRef, useEffect } from 'react';
// 自定义 Hook:返回一个 refs 数组容器和初始化函数
const useDivRefs = (length: number) => {
const refs = useRef<(HTMLDivElement | null)[]>([]);
// 确保 refs.current 长度匹配(避免 stale length)
useEffect(() => {
if (refs.current.length < length) {
refs.current = Array(length).fill(null);
}
}, [length]);
return refs;
};
const MyComponent = () => {
const labels = ['div 1', 'div 2', 'div 3'];
// 创建一个 ref 容器,持有 3 个 null 初始值
const divRefs = useDivRefs(labels.length);
// 示例:滚动到指定索引的元素
const scrollToSection = (index: number) => {
const el = divRefs.current[index];
if (el) el.scrollIntoView({ behavior: 'smooth' });
};
return (
{/* 渲染带 ref 的元素 */}
{labels.map((label, i) => {
const targetId = label.replace(/\s+/g, '');
return (
{
divRefs.current[i] = el; // ✅ 安全:不调用 Hook,仅赋值
}}
style={{ scrollMarginTop: '80px' }} // 可选:避免被固定头部遮挡
>
{label}
Section content...
);
})}
{/* 导航按钮示例 */}
);
};
export default MyComponent;要为动态生成的元素创建多个引用,核心思路是:
这样既彻底规避了 Rules of Hooks 报错,又保持了代码的可维护性与性能(无重复渲染、无额外 Hook 开销)。