在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)移到.attrstype参数:

const Image = styled.img.attrs<IImageProps>(props => ({
  style: { transform: `translate(0, -${props.frame * props.width}px)` },
}))<IImageProps>``

这样,props将成为您的自定义界面以及的所有内置道具img

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React with Typescript 中样式化组件的附加参数

hoc react组件中的样式化组件

React typescript 样式的组件滑块在组件中不起作用

使用样式化组件覆盖React Bootstrap中的嵌套样式

React&Typescript,样式化的组件和子元素

未加载样式化组件-React Typescript Webpack设置

在React中设置样式化的组件,找到相应的组件

在样式化组件中设置 React 组件道具

将道具传递给Typescript中的React样式的组件

React 中样式化组件的可重用性

在React Native中样式化自定义组件

如何使用React在Emotion情感中组成样式化的组件?

React应用中带有动态文本的样式化组件

.map 不是 React 中样式化组件的函数

在React Native中向样式化组件自定义组件添加样式

具有样式化组件的样式化函数中的React.useContext

用样式化的组件覆盖React组件样式

如何在 react 和 typescript 中使用样式化组件重构代码?

样式化组件React HTML元素工厂

React,样式化组件,打字稿错误

不能使用样式化组件将样式应用于React Native中的自定义组件吗?

如何使用样式化组件React重叠样式?

样式化的组件/ React-外部元素上的样式

样式化的组件/ React-片段元素上的样式

React-Router无法正确呈现样式化组件样式

在TypeScript中扩展React组件

如何在Typescript的React Modal中添加带有样式组件的包装器?

如何在React组件中使用样式化组件

通过样式作为React组件中的道具