NextJS Ref.Current为null
我正在尝试使用USEREF获得DIV的高度,但我遇到了一个错误“ Ref.Current Is Null”。
我从React进口了Useref。
我有关参考的代码:
const [height, setHeight] = useState(0);
const ref = useRef(null);
useEffect(() => {
artwork && setHeight(ref.current.scrollHeight)
}, [artwork]);
我将参考文献添加到了我的Div:
<div
ref={ref}
className="some code"
>
我缺少什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当使用具有依赖关系的挂钩,例如,例如代码>使用效果。这里的关键是将您的
ref
添加到依赖项列表中,以便在安装组件并创建div
时再次运行:问题是在您的原始代码,
Artwork
是依赖项列表中的唯一项目,这意味着它将在更改Artwork
时运行。我可以在 Height 添加到依赖项列表中,但是在此示例中,我已将其排除在外)
This scenario is common when using hooks that have dependencies, such as
useEffect
. The key here is to add yourref
to the dependency list, so that it runs again when the component is mounted and thediv
is created:The problem is that in your original code,
artwork
is the only item in the dependency list, which means it will run whenartwork
is changed.I made this testable in CodeSandbox
(Note that the linter wants you to add
height
to the list of dependencies, but for this example I have left it out)确保检查参考和参考文献不是无效的。
make sure check both ref and ref.current is not nullish.