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

React中如何使用react-spring的useSpring Hook?基础代码动画不生效

组件动画失效的核心原因
  • 代码中useSpring生成的动态动画属性未绑定到渲染元素:当前animated.div的style属性仅传入了静态的c1Style对象,useSpring计算出的随时间变化的opacity值完全没有参与元素样式渲染,因此不会出现淡入效果。
react-spring 基础Hook的正确使用规则
  • useSpring的返回值是随动画进程持续更新的样式属性集合,需要与自定义静态样式做对象合并后,再传入animated封装组件的style属性。
  • 只有经过animated封装的DOM元素,才能识别react-spring传入的动态样式值,在动画执行过程中完成实时样式更新,原生普通DOM元素无法承接这类动画属性。
修正后的完整可运行代码
import React from 'react'
import { useSpring, animated } from 'react-spring'

function Comp1() {
  // 定义从opacity 0 过渡到opacity 1的淡入动画规则
  const props = useSpring({ opacity: 1, from: { opacity: 0 } })
  return (
      {/* 合并动态动画属性与自定义静态样式 */}
      <animated.div style={{...props, ...c1Style}}>
        <h1 style={{ color: "white" }}>Component 1</h1>
        <p>It is a long established fact that a reader will be distracted
        by the readable content of a page when looking at its layout.
        The point of using Lorem Ipsum is that it has a more-or-less
        normal distribution of letters, as opposed to using 'Content here,
         content here', making it look like readable English. </p>
      </animated.div>
  )
}

const c1Style = {
  background: 'steelblue',
  color: 'white',
  padding: '1.5rem'
}

export default Comp1

补充提示:如果完成样式合并后动画仍未生效,可核查本地安装的react-spring版本:上述写法适配v9及以上版本的API规则,v8及更早版本的Hook调用格式存在差异。


内容的提问来源于stack exchange,提问作者Somename

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 00:54:01