use*_*457 1 typescript reactjs styled-components
我正在尝试在 React + Typescript 中实现动画。
interface IImageProps {
frame: number
width: number
src: string
onLoad: () => void
}
const Image = styled.img`
transform: ${(props: IImageProps) => css`translate(0, -${props.frame * props.width}px)`};
`
Run Code Online (Sandbox Code Playgroud)
这会在控制台中引发警告:
styled-components.browser.esm.js:1507 Over 200 classes were generated for component styled.img.
Consider using the attrs method, together with a style object for frequently changed styles.
Run Code Online (Sandbox Code Playgroud)
所以我试图使用attrs:
const Image = styled.img.attrs((props: IImageProps) => ({
style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))``
Run Code Online (Sandbox Code Playgroud)
现在 TS 抱怨说:
Type '{ src: string; onLoad: () => void; width: number; frame: number; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<Pick<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, "src" | "width" | "children" | "style" | "title" | ... 255 more ... | "useMap"> & { ...; } & { ...; }, "src" | ... 259 more ... | "useMap"> & Partial<...>, "src" | ... 260 more ... | "useMap"> & { ...;...'.
Property 'frame' does not exist on type 'IntrinsicAttributes & Pick<Pick<Pick<Pick<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, "src" | "width" | "children" | "style" | "title" | ... 255 more ... | "useMap"> & { ...; } & { ...; }, "src" | ... 259 more ... | "useMap"> & Partial<...>, "src" | ... 260 more ... | "useMap"> & { ...;...'.
Run Code Online (Sandbox Code Playgroud)
我可以通过铸造来克服它 const Image = ... `` as any
但我不喜欢那样any。对于熟悉样式组件代码的人来说,这可能是一个简单的答案......
您需要将 添加IImageProps到最终标记的模板调用中,以表明这些是您的样式化组件除了<img>道具之外添加的自定义道具:
const Image = styled.img.attrs((props: IImageProps) => ({
style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))<IImageProps>``
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以将类型注释从 移动(props: IImageProps)到.attrs类型参数:
const Image = styled.img.attrs<IImageProps>(props => ({
style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))<IImageProps>``
Run Code Online (Sandbox Code Playgroud)
这样一来,props将是您的自定义界面加上全内置的道具img。
| 归档时间: |
|
| 查看次数: |
2800 次 |
| 最近记录: |