【问题标题】:Casting styled components in React + Typescript在 React + Typescript 中转换样式组件
【发布时间】:2019-07-05 11:55:55
【问题描述】:

我正在尝试在 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。对于熟悉样式化组件代码的人来说,这可能是一个简单的答案...

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    您需要将 IImageProps 添加到最终的标记模板调用中,以表明这些是您的样式化组件在 &lt;img&gt; 属性之外添加的自定义属性:

    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 的所有内置道具。

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 2021-02-23
      • 2020-06-03
      • 2021-04-13
      • 2021-06-16
      • 2020-05-10
      • 2020-11-05
      • 2021-01-10
      • 2023-03-05
      相关资源
      最近更新 更多