如何正确使用机车卷轴与Next.js走线?

我将locomotive-scroll与Next.js一起使用,一切正常。但在路由到不同页面后,我的卷轴不会损坏,并且两个卷轴相互重叠。

路由后如何在Next.js中正确补位locomotive-scroll

我的代码示例:

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

解决方案

您应该将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>
    );
}

相关文章