React Konva 的“use-image”库抛出 TypeScript 错误

React Konva's `use-image` library throws TypeScript error

完整的错误是:

TS2322: Type '[HTMLImageElement | undefined, "loaded" | "loading" | "failed"]' is not assignable to type 'HTMLImageElement | SVGImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas | undefined'. Type '[HTMLImageElement | undefined, "loaded" | "loading" | "failed"]' is not assignable to type 'OffscreenCanvas'.

我正在尝试使用 https://github.com/konvajs/use-image 比如:

const win = {
  width: window.innerWidth,
  height: window.innerHeight,
}

const App = () => {
  const image = useImage('https://konvajs.org/assets/lion.png')

  return (
    <Stage width={win.width} height={win.height}>
      <Layer>
        <Image image={image} />
      </Layer>
    </Stage>
  )
}

我尝试制作一个 declaration.d.ts 文件,例如:

declare module 'use-image' {
  function useImage(
    url: string,
    crossOrigin?: string
  ): [
    (
      | HTMLImageElement
      | SVGImageElement
      | HTMLVideoElement
      | HTMLCanvasElement
      | ImageBitmap
      | OffscreenCanvas
      | undefined
    ),
    'loaded' | 'loading' | 'failed'
  ]

  export default useImage
}

但它也不起作用。我该如何解决这个问题?

我犯了一个愚蠢的错误。它应该是 [image] 而不是 image:

const [image] = useImage('https://konvajs.org/assets/lion.png')

您没有使用正确的语法应该是 const [image] 而不是 const image