1

我正在尝试使用机车卷轴,但出现错误

在此处输入图像描述

我尝试使用 react-locomotive-scroll 但得到同样的错误

我的_app.tsx长相是这样的

在此处输入图像描述

我的错误在哪里?我尝试将包含整个页面的布局组件放入其中,但它也不起作用

import type { AppProps } from "next/app";
import { ThemeProvider, Global } from "@emotion/react";
import { theme } from "../src/common/theme";
import { globalStyles } from "../src/styles/global";
import { appWithTranslation } from "next-i18next";
import "locomotive-scroll/dist/locomotive-scroll.css";
import { useEffect } from "react";

function MyApp({ Component, pageProps }: AppProps) {
  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 (
    <ThemeProvider theme={theme}>
      <Global styles={globalStyles(theme)} />
      <Component {...pageProps} data-scroll-container />
    </ThemeProvider>
  );
}

export default appWithTranslation(MyApp);

我也用next-transpile-modules

const withTM = require("next-transpile-modules")(["gsap", "locomotive-scroll"]);
4

2 回答 2

0

data-scroll-container发生错误是因为DOM 上不存在具有该属性的元素。

设置data-scroll-container实际上Component不会将属性添加到任何元素。Component是一个 React 组件,而不是 HTML 元素。

您应该添加一个新元素来包装Component并在其上设置属性。

<div data-scroll-container>
    <Component {...pageProps} />
</div>
于 2022-02-11T19:46:37.630 回答
0

对我有用的是这样做:

useEffect(() => {
  ;(async () => {
    try {
      const LocomotiveScroll = (await import('locomotive-scroll')).default
      const dataScrollContainer = document.querySelector(
        '[data-scroll-container]',
      )

      if (!dataScrollContainer) {
        console.warn(
          'locomotive-scroll: [data-scroll-container] dataset was not found. You likely forgot to add it which will prevent Locomotive Scroll to work.',
        )
      }

      window.locomotive = new LocomotiveScroll({
        el: dataScrollContainer ?? undefined,
        smooth: true,
      })
    } catch (error) {}
  })()

  return () => {
    window.locomotive?.destroy()
  }
}, [])

并在某个地方有一个 div data-scroll-container。因此,不要直接加载它,而是异步执行。

于 2022-02-24T01:11:24.803 回答