Loading p5js of react-p5 npm package to NextJS app shows "ReferenceError: window is not defined"

Loading p5js of react-p5 npm package to NextJS app shows "ReferenceError: window is not defined"

这是我的代码,我从 react-p5 typescript Example 那里得到并稍作修改

import Sketch from "react-p5";
import p5Types from "p5";

type InputParameterType = {};

function P5JsComponent({}: InputParameterType) {
  let x = 50;
  const y = 50;

  //See annotations in JS for more information
  const setup = (p5: p5Types, canvasParentRef: Element) => {
    p5.createCanvas(500, 500).parent(canvasParentRef);
  };

  const draw = (p5: p5Types) => {
    p5.background(0);
    p5.ellipse(x, y, 70, 70);
    x++;
  };
  return <Sketch setup={setup} draw={draw} />;
}

export default P5JsComponent;


我的 NextJs 应用程序中的父组件是 'homepage.tsx',它存在于页面目录中。

import Head from "next/head";
import P5JsComponent from "@/components/P5JsComponent";

function homepage() {
  return (
    <div>
      <Head>
        <title>My App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
       <P5JsComponent />
    </div>
  );
}

export default homepage;


我在 运行 此代码时遇到 ReferenceError: window is not defined 错误。

在服务器端渲染中,我们没有来自浏览器的全局变量,例如“window”变量。 P5JsComponent 必须在客户端呈现。

导入没有 SSR 的 P5JsComponent:

const P5JsComponent = dynamic(
  () => import("@/components/P5JsComponent"),
  { ssr: false }
)

参考:https://nextjs.org/docs/advanced-features/dynamic-import