React Class组件和requestAnimationFrame()的问题



我正在尝试使用react和canvas创建一个模式动画。当组件加载时,我在componentDidUpdate方法中触发动画,但在执行一帧后,react在move函数中抛出错误:Uncaught TypeError: Cannot read properties of undefined (reading 'x')

代码:

export default class Canvas extends Component {

constructor(props) {
super(props);
this.canvasRef = createRef();
this.width = parseInt(this.props.width);
this.height = parseInt(this.props.height);
this.x = Math.random(this.props.seed) * this.width;
this.y = Math.random(this.props.seed) * this.height;
this.r = Math.random(this.props.seed) * 20 + 5;
this.dx = 10;
this.dy = 10;
this.color = "#"+Math.floor(Math.random(this.props.seed) * 1000000);
}

componentDidMount () {
console.log("initial view created");
this.ctx = this.canvasRef.current.getContext('2d');
}
componentDidUpdate () {
console.log("updating view");
this.move();
}
draw () {
this.ctx.fillStyle = this.color;
this.ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
this.ctx.fill();
}

//this is the function where the problem might be :
move() {
console.log(this.x, this.y);
this.x += this.dx; //this line propmpts the error
this.y += this.dy;
this.draw();

requestAnimationFrame(this.move)
}
render() {
return (
<canvas
ref={this.canvasRef}
className={this.props.className}
width={this.props.width}
height={this.props.height}
/>
);
}
}

我已经尝试过在没有requestAnimationFrame((的情况下在循环中运行move函数,并且代码运行了,所以我怀疑问题与react或类组件有关。我认为它可能与requestAnimationFrame((有关,但我不明白问题出在哪里

尝试使用箭头函数定义move,如下所示:

move=()=> {
console.log(this.x, this.y);
...
}

使用箭头方法,确保该方法不具有自己的this&使用当前对象作为CCD_ 4。

最新更新