无法阅读 'offsetTop'

cannot read 'offsetTop'

你好,我的朋友们,我在这个项目中使用了 ReactJs,我在控制台中收到了这条消息

Uncaught TypeError: Cannot read properties of undefined (reading 'offsetTop') at (About.js)

顺便说一句,鳕鱼正在工作,但我想知道如何 remove/fix 此消息。鳕鱼:-

  const [start, setStart] = useState(false);
  const secRef = useRef();

  window.addEventListener("scroll", function () {
    const secTop = secRef.current.offsetTop;
    if (window.scrollY >= secTop - 300) {
      setStart(true);
    }
  });

然后我说如果开始是真的添加一些 class,它工作正常但是控制台消息有什么问题?

您的 ref 可能当时尚未初始化。您可以避免如下所示的运行时错误。

  window.addEventListener("scroll", function () {
    if(secRef.current) {
        const secTop = secRef.current.offsetTop;
        if (window.scrollY >= secTop - 300) {
          setStart(true);
        }
    }
  });

这是您需要在安装组件后执行的操作。

您可以使用 React 的 useEffect 钩子来处理此类“副作用”:

useEffect(() => {
    window.addEventListener("scroll", function () {
        const secTop = secRef.current.offsetTop;
        if (window.scrollY >= secTop - 300) {
            setStart(true);
        }
    });
}, []);

我应该注意;卸载组件后,您需要删除此事件侦听器。您可以在 useEffect 函数返回的回调中执行此操作。以下是一个相当常见的模式:

useEffect(() => {
    // Define the on-scroll callback
    const callback = function () {
        const secTop = secRef.current.offsetTop;
        if (window.scrollY >= secTop - 300) {
            setStart(true);
        }
    };

    // Attach the callback after the component mounts
    window.addEventListener("scroll", callback);

    // Detach the callback before the component unmounts
    return () => window.removeEventListener("scroll", callback);
}, []);

此外,根据您的情况,遵循 并检查您的引用是否存在(已呈现)可能仍然是明智的。