当我编写此代码时,出现错误:
React Hook "useRef" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
我应该用这段代码做什么?
return ITEMS.map((item, i) => {
const elementRef = useRef(null);
return (
<div
ref={elementRef}
key={i}
>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item
parentRef={elementRef}
/>
)}
</Wrapper>
</div>
);
}
最佳答案
这里有两种可能性,要么将 useRef
与对象/数组一起使用,要么按照 Yevgen Gorbunkov 的建议使用 createRef
。
我不完全确定这些的可行性,因为 createRef
选项将在每个渲染上创建全新的引用,并且您需要 useRef
选项确保您的键/索引始终相同。
const ITEMS = [{ name: "test" }, { name: "test2" }];
export default function App() {
const ref = useRef({});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{ITEMS.map((item, idx) => {
return (
<div key={idx} ref={element => (ref.current[idx] = element)}>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && (
<Item parentRef={ref.current[idx]} />
)}
</Wrapper>
</div>
);
})}
{ITEMS.map((item, idx) => {
const ref = createRef();
return (
<div key={idx} ref={ref}>
<p>{item.name}</p>
<Wrapper>
{item.name === visibleItem && <Item parentRef={ref} />}
</Wrapper>
</div>
);
})}
</div>
);
}
关于javascript - 为什么我无法在回调中调用 useRef ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61489857/