如何使用 React 和 Typescript 将 html 属性传递给子 <img> 元素,而不出现“IntrinsicAttributes & HTMLAttributes<HTMLImageElement> 错误”?

Joe*_*erg 2 typescript reactjs

我有一个包装图像元素的功能性 React 组件:

type BlobImageProps = HTMLAttributes<HTMLImageElement> & {
    blobId: string
}

function BlobImage(props: BlobImageProps){
    const {blobId, ...htmlAttributes} = props
    const [objectUrl, setObjectUrl] = useState<string>()
    // ...
    // ... load image blob using effect hook
    // ...
    return <img {...htmlAttributes} src={objectUrl}/>
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

function MyPage(){
    //...
    return (
        <BlobImage blobId="xyz1234" alt="Funny cats"/>
    )
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个 typeScript 错误:

Type '{ blobId: string; alt: string; }' is not assignable to type 'IntrinsicAttributes & HTMLAttributes<HTMLImageElement> & { blobId: string; }'.
  Property 'alt' does not exist on type 'IntrinsicAttributes & HTMLAttributes<HTMLImageElement> & { blobId: string; }'.
Run Code Online (Sandbox Code Playgroud)

我打字有什么问题吗?应该有什么类型BlobImageProps

T.J*_*der 13

浏览 React 类型定义,\xc2\xb9 看起来你正在寻找ImgHTMLAttributes<HTMLImageElement>而不是HTMLAttributes<HTMLImageElement>.

\n
\n

\xc2\xb9 我是如何做到的:我将你的类型定义粘贴到我的编辑器中,将光标放在 上HTMLAttributes,并要求它向我显示定义(F12在我的例子中是 VSCode)。它带我去了index.d.tsReact(在@types/reactnode_modules)。我注意到该接口没有alt(并且没有将其类型参数用于任何事情,这看起来很奇怪),所以我搜索alt并找到了ImgHTMLAttributes.

\n