我在使用预加载函数通过 react-p5 库加载图像时遇到问题

I have problem using preload function to load images with react-p5 library

我已经使用 react-p5 库将 P5 库与 React 集成,但是当我使用 preload 函数加载图像时出现错误。问题是,如何让预加载 p5 函数在 React 中处理加载图像?

代码如下:

import React, { Component } from "react";
import Sketch from "react-p5";
import ReactJS from './images/Icons/React.jpg';
let test;
export default class Sket extends Component {
  x = 50
  y = 50

  preload = (p5) =>{
     test = p5.loadImage(ReactJS, ()=>{
        p5.image(test, 0, 0, 50, 50)
     });
  }

  setup = (p5, parent) => { // window width is still not optimized for extra large screen
    var sket = p5.createCanvas(parent.offsetWidth, parent.offsetWidth).parent(parent);
    sket.position(0, 0);
  }
  draw = (p5) => {
    p5.background(0)
    p5.ellipse(this.x, this.y, 70, 70)
    this.x++
    this.y++
  //  p5.image(test, 50, 50)
  }

  render() {
    return <Sketch setup={this.setup} draw={this.draw} />
  }
}

从 URL 加载图像,而不是“从变量”加载图像,因此:

export default class Sketch extends Component {
  constructor(props) {
    super(props);
    // just keep these in your constructor:
    this.x = 50;
    this.y = 50;
  } 

  setup(p5, parent) {
    this.p5 = ps;
    p5.loadImage("./images/blah.jpg", img => {
      this.img = img;
      p5.redraw(); // <- only if you're running with noLoop()
    });
  }

  ...

然后更新绘图以仅在图像存在时绘制图像:

draw() {
  const p5 = this.p5;

  if (this.img) {
    p5.image(this.img, this.x, this.y);
  }

  ...
}

当然:你不能只说 <Sketch setup={this.setup} draw={this.draw}>。该 this 关键字将在运行时指向全局范围。自从 React 16 以来,您要么需要在构造函数中使用 bind 来显式隐藏您的函数(这是一个糟糕的想法),要么使用箭头函数来确保 this 指向它所在的位置申报时间

箭头函数是迄今为止更好的选择:

render() {
  return <Sketch
    setup={(...args) => this.setup(...args)}
    draw={() => this.draw()}
  />;
}