如何将React props传入p5.js sketch并在其中正常访问
React + p5.js 访问传入props的解决方案
报错原因
你在p5的sketch函数内直接引用props变量时,该变量并不在当前作用域内,因此会抛出未定义错误。
解决方法
你当前声明的Sketch类属性已经使用箭头函数定义,this默认绑定到React组件实例,直接访问this.props即可拿到组件接收的所有属性,无需额外绑定。
修复后的完整代码
import React from "react"; import p5 from 'p5'; class Sketch extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } Sketch = (p) => { p.setup = () => { p.createCanvas(400, 400); // 直接通过this.props访问传入的属性 p.print(this.props.name); } p.draw = () => { p.background(0); // draw中也可以直接访问,每次渲染都会拿到最新的props p.fill(this.props.fillColor || 255); p.circle(200, 200, 100); } } componentDidMount() { this.myP5 = new p5(this.Sketch, this.myRef.current); } // 可选配置:响应props更新 componentDidUpdate(prevProps) { // 仅当指定props变化时执行对应逻辑,避免不必要的重绘 if (prevProps.fillColor !== this.props.fillColor) { // 可根据需求调用p5实例的方法更新画布 console.log('填充色更新为', this.props.fillColor); } } // 可选配置:组件卸载时销毁p5实例,避免内存泄漏 componentWillUnmount() { this.myP5.remove(); } render() { return ( <div ref={this.myRef}></div> ) } } export default Sketch;
父组件调用示例
直接按常规React组件的方式传入属性即可:
<Sketch name="测试传入属性" fillColor={180} />
备选写法(普通函数声明Sketch)
如果你没有使用箭头函数声明Sketch,需要手动绑定this指向组件实例:
// 改为普通函数声明 Sketch(p) { p.setup = () => { p.createCanvas(400,400); p.print(this.props.name); } } componentDidMount() { // 调用时绑定this this.myP5 = new p5(this.Sketch.bind(this), this.myRef.current); }
内容的提问来源于stack exchange,提问作者elo
相关产品推荐
相关产品推荐

