Я пытаюсь реализовать анимацию в 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)` },
}))``
теперь ТС жалуется, что:
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.