【问题标题】:Trying to convert React functional component to class component fails尝试将 React 功能组件转换为类组件失败
【发布时间】:2021-01-24 03:29:37
【问题描述】:

我正在尝试在this tutorial 之后使用 React 实现canvas,但我不喜欢在功能组件具有状态或生命周期管理时使用它们(我觉得那是什么类是用于),所以我正在尝试将教程功能组件转换为基于类的组件,这是我附带的代码:

import React from 'react';

class AppCanvas extends React.Component {
  constructor (props) {
    super(props);

    this.canvasRef = React.createRef();
    this.canvas = null;
    this.context = null;
  }

  draw = ctx => {
    ctx.fillStyle = '#00ff66'
    ctx.beginPath()
    ctx.arc(50, 100, 20, 0, 2*Math.PI)
    ctx.fill()
  }

  componentDidMount () {
    this.canvas = this.canvasRef.current;
    this.context = this.canvas.getContext('2d');
    this.context.fillStyle = '#000000';
    this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height);
  }

  render () {
    this.draw(this.context)

    return (
      <canvas className={this.props.classes.canvas} ref={this.canvasRef} />
    )
  }
}

export default AppCanvas;

但我收到以下错误:

×
TypeError: Cannot add property fillStyle, object is not extensible
AppCanvas.draw
src/AppCanvas.js:13
  10 | }
  11 | 
  12 | draw = ctx => {
> 13 |   ctx.fillStyle = '#00ff66'
     | ^  14 |   ctx.beginPath()
  15 |   ctx.arc(50, 100, 20, 0, 2*Math.PI)
  16 |   ctx.fill()

我不知道我做错了什么。

【问题讨论】:

    标签: reactjs html5-canvas react-hooks


    【解决方案1】:

    componentDidMount() 在 render() 之后被调用,在初始 render() 期间 this.context 为 null 并且仅在 componentDidMount() 内部被初始化。

    在 componentDidMount 中移动 this.draw(this.context) 后,代码应如下所示。

    import React from 'react';
    
    
    class AppCanvas extends React.Component {
      constructor (props) {
        super(props);
        this.canvasRef = React.createRef();
        this.canvas = null;
        this.context = null;
      }
    
      draw = ctx => {
        ctx.fillStyle = '#00ff66'
        ctx.beginPath()
        ctx.arc(50, 100, 20, 0, 2*Math.PI)
        ctx.fill()
      }
    
      componentDidMount () {
        this.canvas = this.canvasRef.current;
        this.context = this.canvas.getContext('2d');
        this.draw(this.context)
        this.context.fillStyle = '#000000';
        this.context.fillRect(0, 0, this.context.canvas.width, this.context.canvas.height);
        this.draw(this.context)
      }
    
      render () {
        return (
          <canvas className={this.props.classes.canvas} ref={this.canvasRef} />
        )
      }
    }
    

    App Output

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2020-06-22
      • 2021-05-29
      • 1970-01-01
      • 2021-06-13
      • 2020-06-23
      相关资源
      最近更新 更多