React canvas context.fillRect 不起作用

React canvas context.fillRect doesn't work

我想用 React 画矩形, 下面有什么问题吗?

我不明白为什么这段代码不绘制矩形。


class GameView{
    constructor(props) {
        this.canvas = React.createRef()
        this.width = 0;
        this.height = 0;

        this.canvas_style = {
            width: 600,
            height: 400
        }

    }

    componentDidMount() {
        this.width = document.body.offsetWidth;
        this.height = document.body.offsetHeight;

        this.canvas_style = {
            width: this.width,
            height: this.height
        }

        this.context = this.canvas.current.getContext("2d");
    }

    render() {
        return (
            <canvas id="game-view" ref={this.canvas} width={this.width} height={this.height} />
        )
    }
}
class View extends GameView {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        super.componentDidMount();
        this.context.fillStyle =  "black";
        this.context.fillRect(0, 0, 200, 200)
    }

    render() {
        return (
            <canvas id="game-view" ref={this.canvas} width={this.width} height={this.height} style={this.canvas_style} />
        )
    }
}

我尝试了 docment.getElementById("game-view") 但我得到了相同的结果

GameView 需要扩展 React.Component,以便 React 可以渲染它。

容器的高度(body 在这种情况下)需要大于 0,所以 canvas 会有一些高度。

View 不需要渲染不同的 JSX:

class GameView extends React.Component {
  canvas = React.createRef()
  width = document.body.offsetWidth;
  height = document.body.offsetHeight;  
  
  componentDidMount() {
    this.context = this.canvas.current.getContext("2d");
  }

  render() {
    return (
      <canvas id="game-view" ref={this.canvas} width={this.width} height={this.height} />
    )
  }
}

class View extends GameView {
  componentDidMount() {
    super.componentDidMount();
    this.context.fillStyle = "black";
    this.context.fillRect(0, 0, 200, 200)
  }
}

ReactDOM.render(
  <View />,
  root
);
html, body {
  margin: 0;
  height: 100%;
} 
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>