将 p5 包导入 React 功能组件?

Importing p5 package into a React functional component?

我正在尝试将 p5.js 集成到我的 React 应用程序中。

此处有一个示例说明如何执行此操作:https://dev.to/christiankastner/integrating-p5-js-with-react-i0d

class App extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }

  Sketch = (p) => {

     p.setup = () => {
     ...
     }

     p.draw = () => {
     ...
     }
  }

  componentDidMount() {
    this.myP5 = new p5(this.Sketch, this.myRef.current)
  }

  render() {
    return (
      <div ref={this.myRef}>

      </div>
    )
  }
}

但给出的示例是 Class 组件。

如何将上面的例子转化为功能组件?

我尝试了以下方法:

import React, { useRef } from "react";
import p5 from "p5";

const App = () => {
  const processingRef = useRef();

  const Sketch = p => {
    p.setup = () => {};

    p.draw = () => {};
  };

  const newp5 = new p5(Sketch, processingRef);

  return <div ref={processingRef} />;
};

export default App;

但我在 const newp5 = new p5(Sketch, processingRef):

行被抛出错误
this._userNode.appendChild is not a function

您应该先等待 ref 设置:

import React, { useRef } from "react";
import p5 from "p5";

const App = () => {
  const setProcessingRef = (element) => {
    if (element) {
      const Sketch = (p) => {
        p.setup = () => {};

        p.draw = () => {};
      };

      const newp5 = new p5(Sketch, processingRef);
    }
  };

  return <div ref={setProcessingRef} />;
};

export default App;

import React, { useRef, useEffect } from "react";
import p5 from "p5";

const App = () => {
  const processingRef = useRef();
  const Sketch = p => {
    p.setup = () => {};

    p.draw = () => {};
     };
   useEffect(() => {
    const newp5 = new p5(Sketch, processingRef.current);
    }, [])

  return <div ref={processingRef} />;
};

export default App;

Passing no dependency in the useEffect hook makes it run once just like the componentDidMount Live Cycle Method