Aya*_*qui 9 typeerror typescript reactjs
我正在开发一个组件,该组件接受一个子属性,该子属性接受一个img元素+另一个属性。但是当我继续使用该组件并传递所有道具时,我收到以下错误:
类型“Element”与类型“Pick<ImgHTMLAttributes, "src" | 没有共同的属性 “替代”>'.ts(2559)
App.tsx(5, 3):预期类型来自属性“children”,该属性在类型“IntrinsicAttributes & Props”上声明
这是我的代码示例(链接到 CodeSandbox):
type Props = {
children: Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt">
otherProp?: any
}
const Image = ({children, otherProp}: Props) => {
return (
<picture>
...
{children}
</picture>
)
}
Run Code Online (Sandbox Code Playgroud)
老实说,我不明白是什么IntrinsicAttributes,我可以看到它正在Prop用其他类型扩展我的功能IntrinsicAttributes,但不确定到底为什么。当我删除otherProp. 一个解释真的很有帮助。多谢。
类型ImgHTTMLAttributes<HTMLImageElement>是描述简单对象的类型,包含imgjsx元素可以接受的所有属性。
Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt">只是一种类型{ src: string; alt: string }。请注意,它并不描述实际的imgjsx 元素,它只是描述它可能具有的 props。
在打字稿中,没有办法说“这个组件只接受img只有 propsalt和的 jsx 元素src”,所以没有办法输入这个,至少不像你在沙箱中显示的那样。children你可能应该做的是首先摆脱它,然后直接src传递alt到Image组件
interface Props {
src: string
alt: string
otherProp?: any;
}
const Image = ({ src, alt, otherProp }: Props) => {
return <picture><img src={src} alt={alt} /></picture>;
};
const el = <Image otherProp="" src="cool" alt="Image alt tag" />
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想为自己编写类型定义src,alt则可以像在示例中那样获取现有类型ImgHTTMLAttributes,但它应该如下所示:
type Props = Pick<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt"> & {
otherProp?: any;
}
const Image = ({ src, alt, otherProp }: Props) => {
return <picture><img src={src} alt={alt} /></picture>;
};
const el = <Image otherProp="" src="cool" alt="Image alt tag" />
Run Code Online (Sandbox Code Playgroud)
说到IntrinsicAttributes,这是一种描述所有组件都可以接收的 props 的类型,即使您没有在 props 定义中提供它们。它们通常由库内部使用,这就是它们被称为内在的原因。例如,如果您使用react,唯一的内在属性是key:您可以将其附加到任何组件,而无需在任何地方定义其类型,并且它由react内部使用。当您使用任何 jsx 组件时,其 prop 类型由 type 描述IntrinsicAttributes & PropsThathYouDefinedForYourComponent,在您的情况下为IntrinsicAttributes & Props。这样,当您使用这个 jsx 组件时,您可以传递自定义 props 和内部库 props,并且类型检查仍然有效
| 归档时间: |
|
| 查看次数: |
65787 次 |
| 最近记录: |