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

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

TypeScript: 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'

问题

  1. 我正在尝试使用 useRef 获取对画布的引用,但 TypeScript 报错。
  2. ```javascript
  3. import React, { useRef } from 'react';
  4. const AddPhoto: React.FC = () => {
  5. const canvas = useRef<HTMLCanvasElement>(null);
  6. const ctx: CanvasRenderingContext2D = canvas.current!.getContext('2d')!;
  7. // ^ 错误
  8. }
  9. return (
  10. <canvas
  11. ref={canvas}
  12. width={315}
  13. height={315}
  14. />
  15. )

我收到的错误是:

  1. Property 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'.ts(2339)

如果我将代码更改为:

  1. if (canvas && canvas.current) {
  2. const ctx: CanvasRenderingContext2D = canvas.current.getContext('2d');
  3. // ^ 错误
  4. }

现在的错误是:

  1. Type 'CanvasRenderingContext2D | null' is not assignable to type 'CanvasRenderingContext2D'.
  2. Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)
  1. <details>
  2. <summary>英文:</summary>
  3. 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}
/>
)

  1. The error I get is

Property 'getContext' does not exist on type 'RefObject<HTMLCanvasElement>'.ts(2339)

  1. if I change it to
  1. if (canvas &amp;&amp; canvas.current) {
  2. const ctx: CanvasRenderingContext2D = canvas.current.getContext(&#39;2d&#39;);

// ^error

  1. }
  1. the error is now

Type 'CanvasRenderingContext2D | null' is not assignable to type 'CanvasRenderingContext2D'.
Type 'null' is not assignable to type 'CanvasRenderingContext2D'.ts(2322)

  1. </details>
  2. # 答案1
  3. **得分**: 2
  4. 使用 `useRef` 时,您的值不仅存储在 `canvas` 变量中,还存储在 `canvas.current` 中,因此应使用 `canvas.current.getContext('2d')`。
  5. 要修复类型问题,请使用这个替代 `if (...) {...}`
  6. ```typescript
  7. 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(...){...}

  1. 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:

确定