将 p5.js 合并到 Next.js (React App) 网站中

incorporating p5.js in a Next.js (React App) website

我有一个 运行 在本地主机上完美运行的 React 应用程序。但是当我将它添加到我的 Next.js (React.js) 网站时,它说 "ReferenceError: window is not defined." 我认为这是因为我在 运行ning P5.js [=21] =] 但它只能在浏览器上 运行 。我该如何解决这个问题?

我在 React 应用程序中的 P5.js 草图

import React, { Component } from 'react';
// import logo from './logo.svg';
import p5 from 'p5';


class Sketch extends Component {
  constructor(){
  super()
  this.renderRef = React.createRef()
  this.state = {
    x: 100,
    y: 100
    }
  }

  componentDidMount(){
    this.sketch = new p5( p => {

      p.setup = ()  => {
          p.createCanvas(p.windowWidth, p.windowHeight)
          .parent(this.renderRef.current);
          p.background('white');
          p.strokeWeight(5);

      }
      p.windowResized = () => {
          p.resizeCanvas(p.windowWidth, p.windowHeight )
      }

      p.draw = () => {
          if(p.mouseIsPressed){
              p.stroke(225)
          } else{
              p.stroke(0, 0, 0);
          }
          p.line(p.mouseX , p.mouseY, p.mouseX , p.mouseY);
          p.line(p.mouseX, p.mouseY , p.mouseX, p.mouseY);
          }

        });


    }
render(){

return (
  <div className="App">
    <div ref={this.renderRef}></div>
  </div>
);
}
}

export default Sketch;

componentDidMount

中导入 p5
componentDidMount(){
    const p5 = require("p5")
    this.sketch = new p5( p => {
    ...

在 NextJS 中,componentDidMount() 仅在 window 和其他浏览器特定 API 可用的客户端执行。看看这个