我想增加通过this.setState({count: this.state.count + 1});
单击浏览器中反弹的球的次数。我认为我的代码中的内容应该可以工作,因为我之前没有使用画布就已经做到了,但是它不起作用。
我的代码在做什么错,我该如何解决?
import React, { Component } from 'react';
import './Main.css';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
let c = document.getElementById("mycanvas");
let cxt = c.getContext("2d");
let x = 0;
let y = 0;
let r = 10;
let dx = 4;
let dy = 8;
let WIDTH = 240;
let HEIGHT = 240;
c.onclick = function () {
this.setState({count: this.state.count + 1});
};
function init() {
window.requestAnimationFrame(init, cxt);
draw();
}
function drawCircle(x, y, r) {
cxt.clearRect(0, 0, 240, 240);
cxt.beginPath();
cxt.arc(x, y, r, 0, Math.PI * 2, false);
cxt.fillStyle = "#006699";
cxt.fill();
}
function draw() {
drawCircle(x, y, r);
if(x + dx > WIDTH || x + dx < 0) {
dx = -dx;
// console.log(dx);
}
if(y + dy > HEIGHT || y + dy < 0){
dy = -dy;
}
x += dx;
y += dy;
}
init();
}
render() {
return(
<div>
<canvas id="mycanvas" width="240" height="240"/>
<h1>{this.state.count}</h1>
</div>
);
}
}
export default Main;
这是错误:
TypeError: Cannot read property 'count' of undefined
HTMLCanvasElement.c.onclick
src/containers/Main/Main.js:25
22 | let HEIGHT = 240;
23 |
24 | c.onclick = function () {
> 25 | this.setState({count: this.state.count + 1});
26 | };
27 |
28 | function init() {
答案 0 :(得分:2)
this
在函数作用域内为window
。因此,您将需要绑定this
:
c.onclick = function () {
this.setState({count: this.state.count + 1});
}.bind(this);
此外,我建议您使用箭头功能,并将setState与这样的更新程序一起使用:
c.onclick = () => {
this.setState(prevState => ({count: prevState.count+1})
}