首页 > 解决方案 > reactjs 中的 createRef 给出错误(this.canvas.current 始终为空)

问题描述

我想向画布元素添加一个引用。
我的代码是-

componentDidMount(){
        const canvas = this.canvas.current
        console.log(canvas)
        const ctx = canvas.getContext('2d')
        const img = this.memeImage
    }

构造函数包含

this.canvas = React.createRef()
this.memeImage = React.createRef()

jsx 元素是 -

<canvas ref={this.canvas} height='400px' width='400px' />
<img ref={this.memeImage} width='300px' src={imageArray[0].url} alt='not found' />

我得到的错误是

TypeError: Cannot read property 'getContext' of null
  28 |    componentDidMount(){
  29 |        const canvas = this.canvas.current
  30 |        console.log(canvas)
> 31 |        const ctx = canvas.getContext('2d')
  32 |^        const img = this.memeImage
  33 |    }
  34 |

我做到console.log(this.canvas)了-current: null
我在这里做错了什么?

标签: javascriptreactjscanvas

解决方案


推荐阅读