【问题标题】:Why won't my counter work upon clicking the canvas?为什么我的计数器在单击画布时不起作用?
【发布时间】:2018-11-05 17:06:54
【问题描述】:

我想增加在浏览器中弹跳的球通过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() {

【问题讨论】:

    标签: javascript html reactjs debugging canvas


    【解决方案1】:

    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})
    }
    

    【讨论】:

    • 谢谢你,我在这个过程中犯了一些粗心的错误。
    • @sp92 没问题
    猜你喜欢
    • 2021-10-28
    • 2017-03-12
    • 2019-08-18
    • 2022-11-29
    • 2022-01-17
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多