我试图使用useRef获得div的高度,但我得到一个错误"ref。电流为空。
我从React导入了useRef。
关于ref:
const [height, setHeight] = useState(0);
const ref = useRef(null);
useEffect(() => {
artwork && setHeight(ref.current.scrollHeight)
}, [artwork]);
我给div添加了ref:
<div
ref={ref}
className="some code"
>
我错过了什么?
确保ref和ref.current都不是null
useEffect(() => {
if(ref && ref.current) {
artwork && setHeight(ref.current.scrollHeight)
}
}, [artwork]);
当使用有依赖关系的钩子时,这种情况很常见,比如useEffect
。这里的关键是将ref
添加到依赖项列表中,以便在挂载组件并创建div
时再次运行:
function Component({ artwork }) {
const [height, setHeight] = useState(-1);
const ref = useRef();
useEffect(() => {
if(artwork && ref?.current) {
console.log('setting');
setHeight(ref.current.scrollHeight);
}
}, [artwork, ref]);
return (
<div ref={ref} className="some code">{height}</div>
);
}
问题是,在您的原始代码中,artwork
是依赖项列表中的唯一项,这意味着当artwork
更改时它将运行。
...
}, [artwork]);
我在CodeSandbox中做了这个测试
(注意,linter希望您将height
添加到依赖项列表中,但对于本例,我省略了它)