如何为React UseAnimations组件添加正确类型?解决属性报错
问题代码
import React from 'react' import UseAnimations from 'react-useanimations' const Animation: React.FC = () => { return ( <React.Fragment> <UseAnimations animationKey="github" size={56} style={{ padding: 100 }} /> </React.Fragment> ) } export default Animation
报错信息
Type '{ animationKey: string; size: number; style: { padding: number; }; }' is not assignable to type 'IntrinsicAttributes & { animation: Animation; reverse?: boolean | undefined; strokeColor?: string | undefined; fillColor?: string | undefined; ... 7 more ...; render?: ((eventProps: any, animationProps: any) => ReactElement<...>) | undefined; } & HTMLProps<...>'.
Property 'animationKey' does not exist on type 'IntrinsicAttributes & { animation: Animation; reverse?: boolean | undefined; strokeColor?: string | undefined; fillColor?: string | undefined; ... 7 more ...; render?: ((eventProps: any, animationProps: any) => ReactElement<...>) | undefined; } & HTMLProps<...>'. Did you mean 'animation'?
解决方案
错误提示已明确指出问题:animationKey不是UseAnimations组件的合法属性,正确属性名为animation,且需要传入动画对象而非字符串key。以下是两种正确实现方式:
方式一:直接导入指定动画
import React from 'react' import UseAnimations from 'react-useanimations' // 直接导入github动画对象 import githubAnimation from 'react-useanimations/lib/github' const Animation: React.FC = () => { return ( <> <UseAnimations animation={githubAnimation} size={56} style={{ padding: 100 }} /> </> ) } export default Animation
方式二:动态获取动画对象
如果需要动态切换动画,可使用getAnimation方法获取对应动画对象:
import React from 'react' import UseAnimations, { getAnimation } from 'react-useanimations' const Animation: React.FC = () => { // 通过字符串key获取动画对象 const githubAnimation = getAnimation('github') return ( <> <UseAnimations animation={githubAnimation} size={56} style={{ padding: 100 }} /> </> ) } export default Animation
说明
react-useanimations新版本API已不再支持animationKey字符串参数,改为要求传入具体动画对象,这样能更好地配合TypeScript做类型检查,避免属性不匹配问题。
内容的提问来源于stack exchange,提问作者Teshane Crawford

