window.addEventListener('load', function) 在react(gatsby) 中不起作用

han*_*001 3 javascript parallax reactjs gatsby

当页面初始滚动不在加载时的顶部时,我正在努力解决滚动视差问题。我使用react-scroll-parallax库(https://www.npmjs.com/package/react-scroll-parallax)。为了解决我的问题,我尝试使用他们的建议https://www.npmjs.com/package/react-scroll-parallax#example-usage-of-context

import { useEffect } from 'react';
import { useController } from 'react-scroll-parallax';

const ParallaxCache = () => {
  const { parallaxController } = useController();
  useEffect(() => {
    const handler = () => {
      parallaxController.update();
      console.log(1);
    };
    window.addEventListener('load', handler);
    return () => document.removeEventListener('load', handler);
  }, [parallaxController]);

  return null;
};

export default ParallaxCache;
Run Code Online (Sandbox Code Playgroud)

我将 ParallaxCache 组件放在我的应用程序顶部(实际上是页面,因为它是 gatsby)。

但“加载”事件似乎不起作用。我也尝试过“DOMContentLoaded”,但结果相同。然而,其他事件(例如“滚动”或“调整大小”)可以正常工作,并且我的控制器会更新。我是否遗漏了某些内容或反应阻止使用此事件?

Ben*_*ick 7

如果只是load事件不起作用,则运行此代码时页面可能已经加载。尝试添加 if 语句来检查文档是否已加载。

import { useEffect } from 'react';
import { useController } from 'react-scroll-parallax';

const ParallaxCache = () => {
  const { parallaxController } = useController();
  useEffect(() => {
    const handler = () => {
      parallaxController.update();
      console.log(1);
    };

    if (document.readyState === "complete") {
      handler();
    } else {
      window.addEventListener('load', handler);
      return () => document.removeEventListener('load', handler);
    }
  }, [parallaxController]);

  return null;
};

export default ParallaxCache;
Run Code Online (Sandbox Code Playgroud)