我正在尝试将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
答案 0 :(得分:1)
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;
在 useEffect 挂钩中不传递任何依赖关系使其像 componentDidMount 实时循环方法
一样运行一次
答案 1 :(得分:0)
您应该等待首先设置参考:
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;