You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为React UseAnimations组件添加正确类型?解决属性报错

解决react-useanimations组件的TypeScript类型错误

问题代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:27:36