NextJS Ref.Current为null

发布于 2025-01-26 08:00:24 字数 468 浏览 1 评论 0 原文

我正在尝试使用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"
            
    >

我缺少什么?

I'm trying to get the height of a div using useRef but I get an error "ref.current is null".
I imported useRef from React.

My code concerning ref :

    const [height, setHeight] = useState(0);
    const ref = useRef(null);

    useEffect(() => {
        artwork && setHeight(ref.current.scrollHeight)
    }, [artwork]);

And I added the ref to my div :

    <div
        ref={ref}
        className="some code"
            
    >

What am I missing ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽清梦 2025-02-02 08:00:24

当使用具有依赖关系的挂钩,例如,例如代码>使用效果。这里的关键是将您的 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]);

我可以在 Height 添加到依赖项列表中,但是在此示例中,我已将其排除在外)

This scenario is common when using hooks that have dependencies, such as useEffect. The key here is to add your ref to the dependency list, so that it runs again when the component is mounted and the div is created:

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>
    );
}

The problem is that in your original code, artwork is the only item in the dependency list, which means it will run when artwork is changed.

   ...
}, [artwork]);

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)

打小就很酷 2025-02-02 08:00:24

确保检查参考和参考文献不是无效的。

 useEffect(() => {
   if(ref && ref.current) {
      artwork && setHeight(ref.current.scrollHeight)
   }
 }, [artwork]);

make sure check both ref and ref.current is not nullish.

 useEffect(() => {
   if(ref && ref.current) {
      artwork && setHeight(ref.current.scrollHeight)
   }
 }, [artwork]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文