error ReferenceError:文档未定义,无法读取未定义的属性(读取“style”)(NextJS 自定义轮播错误)

error ReferenceError: document is not defined and cannot read properties of undefined (reading 'style') (NextJS Custom Carousel bug)

提问人:Ralph Henry 提问时间:5/25/2023 更新时间:5/25/2023 访问量:347

问:

我创建了一个自定义轮播组件,用于显示文本证词。此自定义轮播是从头开始制作的,它使用自定义脚本功能 () 进行箭头导航,以遍历到显示的每个文本证词。轮播界面如下所示:carouselFunction.js

Custom Carousel

我在 NextJS 中的自定义轮播有问题。我在我的文件中得到了一个(用于轮播功能的 JS 文件),我不确定为什么它会引发该错误,因为我只获得了我的自定义轮播组件 () 的 div 的类名“textimony”,并将该类名分配给 slides 变量,该变量将在 .ReferenceError: document is not definedcarouselFunction.jsCarousel.tsxcarouselFunction.js

源代码:carouselFunction.js

let slideIndex = 0;
showSlides(slideIndex);

export function changeSlides(n) {
  showSlides((slideIndex += n));
}

export function showSlides(n) {
  let i;
  let slides = document.getElementsByClassName("textimony");

  n > slides.length - 1
    ? (slideIndex = 1)
    : n < 0
    ? (slideIndex = slides.length - 1)
    : null;

  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slides[slideIndex].style.display = "flex";
}

源代码:Carousel.tsx

"use client";
import React from "react";
import Image from "next/image";
import "/app/globals.css";
import Script from "next/script";
import { changeSlides } from "../Constants/Carousel_Function/carouselFunction.js";
import leftArrow from "../resources/Shape Elements/left-arrow.webp";
import rightArrow from "../resources/Shape Elements/right-arrow.webp";

const SaliyabCarousel = () => {
  return (
    <div>
      <div className="textimony">
        <a className="left-arrow" onClick={() => changeSlides(-1)}>
          <Image src="" width="107" height="104" alt="left arrow pic" />
        </a>
        <q>
          Saliyab&apos;s workshop was a game-changer for me. The insights and
          practical advice I gained from the experts in the field helped me to
          take my skills to the next level and make a real impact in my work. I
          highly recommend it!
        </q>
        <a className="right-arrow" onClick={() => changeSlides(1)}>
          <Image
            className="right-arrow"
            src={rightArrow}
            width="106"
            height="104"
            alt="right arrow pic"
          />
        </a>
      </div>

      <div className="textimony">
        <a className="left-arrow" onClick={() => changeSlides(-1)}>
          <Image
            src={leftArrow}
            width="107"
            height="104"
            alt="left arrow pic"
          />
        </a>
        <q>
          I&apos;ve attended several workshops in the past, but Saliyab&apos;s
          was by far the most informative and engaging. The speakers were
          knowledgeable and approachable, and I left feeling motivated and
          inspired to pursue new opportunities in the tech industry.
        </q>
        <a className="right-arrow" onClick={() => changeSlides(1)}>
          <Image
            className="right-arrow"
            src={rightArrow}
            width="106"
            height="104"
            alt="right arrow pic"
          />
        </a>
      </div>

      <div className="textimony">
        <a className="left-arrow" onClick={() => changeSlides(-1)}>
          <Image
            src={leftArrow}
            width="107"
            height="104"
            alt="left arrow pic"
          />
        </a>
        <q>
          The Saliyab workshop provided me with a wealth of new information and
          resources that I could immediately apply to my work. I appreciated the
          hands-on approach and the chance to network with other professionals
          in the field.
        </q>
        <a className="right-arrow" onClick={() => changeSlides(1)}>
          <Image
            className="right-arrow"
            src={rightArrow}
            width="106"
            height="104"
            alt="right arrow pic"
          />
        </a>
      </div>

      <div className="textimony">
        <a className="left-arrow" onClick={() => changeSlides(-1)}>
          <Image
            src={leftArrow}
            width="107"
            height="104"
            alt="left arrow pic"
          />
        </a>
        <q>
          As a beginner in the tech industry, I was a bit intimidated to attend
          the Saliyab workshop. But I&apos;m so glad I did! The workshop was
          tailored to all skill levels and I left with a much deeper
          understanding of the field and its possibilities.
        </q>
        <a className="right-arrow" onClick={() => changeSlides(1)}>
          <Image
            className="right-arrow"
            src={rightArrow}
            width="106"
            height="104"
            alt="right arrow pic"
          />
        </a>
      </div>
      <Script src="../Constants/Carousel_Function/carouselFunction.js" />
    </div>
  );
};

export default SaliyabCarousel;

ReferenceError 图片:ReferenceErrorpic

不仅如此,我还得到了一个,我认为这是由于上述原因。TypeError: Cannot read properties of undefined (reading 'style')ReferenceError

TypeError 图片:TypeErrorPic

我已经在我的布局页面上调用了,但错误仍然存在。ScriptcarouselFunction.js

源代码:layout.tsx

import { Inter } from "next/font/google";
import Script from "next/script";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Saliyab Website",
  description: "Saliyab Website using NextJS",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <meta charSet="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <link rel="preconnect" href="https://fonts.googleapis.com" />
      <link
        rel="preconnect"
        href="https://fonts.gstatic.com"
        crossOrigin="anonymous"
      />
      <link
        href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap"
        rel="stylesheet"
      />
      <Script src="../Constants/Carousel_Function/carouselFunction.js" />

      <body className={inter.className}>{children}</body>
    </html>
  );
}

我仍在学习 NextJS 的诀窍,在 NextJS 中创建自定义轮播时获得指南和反馈将有很大帮助。我知道组件库(如Material UI等)中的现有轮播。但我只是想尝试创建一个我的定制版本。

你的回答确实对我完成这项任务有很大帮助。谢谢!

javascript reactjs next.js react-hooks getelementsbyclassname

评论


答:

1赞 ionosphere 5/25/2023 #1

客户端组件在服务器上预呈现,因此它们无权访问 .有几种方法可以解决此错误:document

  1. 加载后访问其中的文档useEffect
  2. 在访问文档之前检查窗口是否未定义。

对于第一种方法,您可以使用 useEffect 将 carouselFunction.js 转换为自定义钩子,或者对于第二种方法,在访问文档之前在 carouselFunction.js 中执行检查。

有关更多详细信息,请参阅以下帖子,其中包含这两种方法的大量示例:

参考错误:未在 Next.js 客户端组件中定义文档

下一页 .js:文档未定义