如何在 Next.js 路由中正确使用 Locomotive Scroll?

IT技术 javascript reactjs next.js locomotive-scroll
2021-05-14 23:12:15

我正在使用locomotive-scrollNext.js 并且一切正常。但是在路由到不同的页面后,我的卷轴不会破坏并且 2 个卷轴彼此重叠。

locomotive-scroll路由后如何在 Next.js 中正确重新初始化?

我的代码示例:

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        import("locomotive-scroll").then((locomotiveModule) => {
            let scroll = new locomotiveModule.default({
                el: document.querySelector("[data-scroll-container]"),
                smooth: true,
                smoothMobile: false,
                resetNativeScroll: true,
             });
          
             scroll.destroy();  //<-- DOESN'T WORK OR IDK
    
             setTimeout(function () {
                 scroll.init();
             }, 400);
         });
     });
    
     return (
         <main data-scroll-container>
             <Component {...pageProps} />
         </main>
     );
}
1个回答

您应该将scroll.destroy调用移至useEffect. 您也不需要显式调用scroll.init().

function MyApp({ Component, pageProps }) {
    useEffect(() => {
        let scroll;
        import("locomotive-scroll").then((locomotiveModule) => {
            scroll = new locomotiveModule.default({
                el: document.querySelector("[data-scroll-container]"),
                smooth: true,
                smoothMobile: false,
                resetNativeScroll: true
            });
        });

        // `useEffect`'s cleanup phase
        return () => scroll.destroy();
    });

    return (
        <main className="main" data-scroll-container>
            <Layout>
                <Component {...pageProps} />
            </Layout>
        </main>
    );
}