‘TypeScript: “getContext” does not exist on type “RefObject“.’

huangapple go评论117阅读模式
英文:

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&#39;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 &amp;&amp; canvas.current) {
  const ctx: CanvasRenderingContext2D = canvas.current.getContext(&#39;2d&#39;);

// ^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(&#39;2d&#39;).


To fix type problem, use this instead of if(...){...}

const ctx: CanvasRenderingContext2D | null = canvas.current ? canvas.current.getContext(&#39;2d&#39;) : null;

huangapple
  • 本文由 发表于 2020年1月3日 22:52:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定