簡體   English   中英

為什么單擊畫布后計數器無法工作?

[英]Why won't my counter work upon clicking the canvas?

我想增加通過this.setState({count: this.state.count + 1});點擊瀏覽器中反彈的球的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() {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM