reactjs - 在 React + Typescript 中转换样式组件
问题描述
我正在尝试在 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)`};
`
这会在控制台中引发警告:
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.
所以我正在尝试使用attrs
:
const Image = styled.img.attrs((props: IImageProps) => ({
style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))``
现在 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"> & { ...;...'.
我可以通过铸造来克服它const Image = ... `` as any
但我不喜欢那样any
。对于熟悉样式化组件代码的人来说,这可能是一个简单的答案......
解决方案
您需要将 添加IImageProps
到最终标记的模板调用中,以表明这些是您的样式化组件除了道具之外添加的自定义<img>
道具:
const Image = styled.img.attrs((props: IImageProps) => ({
style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))<IImageProps>``
请注意,您还可以将类型注释从 移动(props: IImageProps)
到.attrs
类型参数:
const Image = styled.img.attrs<IImageProps>(props => ({
style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))<IImageProps>``
这样,props
将是您的自定义界面以及img
.
推荐阅读
- excel - 即使结果为空白,当我将公式复制并粘贴为值时,Excel 也可能会插入隐藏字符 - 我该如何避免?
- php - 从多个函数中访问数据
- css - 如何在闪亮进度条的详细信息中添加换行符?
- javascript - Fetch API POST 请求响应返回空文本
- c++ - 如何在单独的源文件中定义模板函数并调用它,只包括标题
- ios - 类型不符合协议“可编码”
- konvajs - 向 Konva 形状添加描边而不增加其大小
- javascript - javascript scrollIntoView 函数在我的全局事件侦听器中不起作用
- javascript - 如何将 DOM 数据转换为 json
- html - 圆形元素上的框阴影