const ref = useRef(null);
return (
<>
{ref.current !== null &&
createPortal(<span>Hello!</span>, ref.current as any)}
<div ref={ref}></div>
</>
);
据我了解门户网站,span
应该附加到 div
,但事实并非如此。
为什么会这样?
最佳答案
对 refs 的更改不会触发更新(重新渲染)。我的猜测是您的组件只渲染一次,设置了 ref.current
,但没有重新渲染,所以您看不到 span
。
对于这种情况,您最好使用 callback ref :
const onRef = element => {
if (element !== null) {
createPortal(<span>Hello!</span>, element);
}
};
return <div ref={onRef}></div>;
关于reactjs - 使用 useRef react createPortal 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59514598/