在React + Typescript中铸造样式化的组件

时间:2019-02-11 22:05:55

标签: reactjs typescript 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)`};
`

这会在控制台中引发警告:

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。对于熟悉样式化组件代码的人来说,这也许是一个简单的答案...

1 个答案:

答案 0 :(得分:3)

您将希望将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将成为您的自定义界面 plus img的所有内置道具。