英文:
TypeScript: 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'
问题
我正在尝试使用 useRef 获取对画布的引用,但 TypeScript 报错。
```javascript
import React, { useRef } from 'react';
const AddPhoto: React.FC = () => {
const canvas = useRef<HTMLCanvasElement>(null);
const ctx: CanvasRenderingContext2D = canvas.current!.getContext('2d')!;
// ^ 错误
}
return (
<canvas
ref={canvas}
width={315}
height={315}
/>
)
我收到的错误是:
Property 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'.ts(2339)
如果我将代码更改为:
if (canvas && canvas.current) {
const ctx: CanvasRenderingContext2D = canvas.current.getContext('2d');
// ^ 错误
}
现在的错误是:
Type 'CanvasRenderingContext2D | null' is not assignable to type 'CanvasRenderingContext2D'.
Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)
<details>
<summary>英文:</summary>
I'm trying to useRef to get a refenrece to the canvas but typescript is complaining
import React, { useRef } from 'react';
const AddPhoto: React.FC = () => {
const canvas = useRef<HTMLCanvasElement>(null);
const ctx: CanvasRenderingContext2D = canvas.getContext('2d')!;
// ^ error
}
return (
<canvas
ref={canvas}
width={315}
height={315}
/>
)
The error I get is
Property 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'.ts(2339)
if I change it to
if (canvas && canvas.current) {
const ctx: CanvasRenderingContext2D = canvas.current.getContext('2d');
// ^error
}
the error is now
Type 'CanvasRenderingContext2D | null' is not assignable to type 'CanvasRenderingContext2D'.
Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)
</details>
# 答案1
**得分**: 2
使用 `useRef` 时,您的值不仅存储在 `canvas` 变量中,还存储在 `canvas.current` 中,因此应使用 `canvas.current.getContext('2d')`。
要修复类型问题,请使用这个替代 `if (...) {...}`
```typescript
const ctx: CanvasRenderingContext2D | null = canvas.current ? canvas.current.getContext('2d') : null;
英文:
As you use useRef
, your value stores not just in canvas
variable, but in canvas.current
, so you should use canvas.current.getContext('2d')
.
To fix type problem, use this instead of if(...){...}
const ctx: CanvasRenderingContext2D | null = canvas.current ? canvas.current.getContext('2d') : null;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论