javascript - 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
我在这里做错了什么?
解决方案
推荐阅读
- angular - 在 Angular 服务中编写可共享的方法
- matlab - 实现涉及双重求和的脉冲响应
- python - 在 python 中使简单的绘图平滑
- java - Gradle 使用最新版本的 TestNG 而不是声明的版本
- anylogic - 如何使资源沿着通往代理的路径移动
- ios - 如何在 fastlane 中更改匹配步骤的用户帐户设置?
- javascript - 如何故意使本机应用程序崩溃?
- java - 无法将 MySQL 数据库连接到我的 spring 项目(尽管我已经阅读了所有帖子)
- react-quill - 我无法在 Safari 上的 React-Quill 编辑器中粘贴文本
- c++ - 派生类使用的抽象类方法