React Spring中如何为动画值添加vw、%等单位?
React Spring 动画添加单位的正确方式
你的代码有两个关键问题导致动画失效:
- 直接把
animatedProps对象和字符串拼接是错误的——animatedProps是 React Spring 返回的包含动画值的对象,不是单个数值,无法直接拼接字符串。 - 样式属性拼写错误:
bacgroundColor应该是backgroundColor。
下面是两种正确的实现方式:
方法一:在动画配置中直接指定单位
最简单的方式是在 useSpring 的 from 和 to 里直接写带单位的字符串,React Spring 会自动识别并处理带单位的动画:
import { useSpring, animated } from "react-spring"; export default function App() { const animatedProps = useSpring({ from: { width: "0vw" }, to: { width: "100vw" }, duration: 12000, // 建议用数字类型的毫秒值,字符串也支持但数字更规范 }); return ( <animated.h1 style={{ ...animatedProps, backgroundColor: "red", // 修正拼写错误 }} > <div>Hello CodeSandbox</div> </animated.h1> ); }
方法二:使用 interpolate 动态拼接单位
如果需要动态计算数值(比如从变量获取数值再添加单位),可以用 React Spring 的 interpolate 方法处理动画值:
import { useSpring, animated } from "react-spring"; export default function App() { const animatedProps = useSpring({ from: { width: 0 }, to: { width: 100 }, duration: 12000, }); return ( <animated.h1 style={{ backgroundColor: "red", // 对width属性单独做插值处理 width: animatedProps.width.interpolate((value) => `${value}vw`), }} > <div>Hello CodeSandbox</div> </animated.h1> ); }
注意:第二种方法里不要同时解构 animatedProps 再单独设置 width,否则会覆盖。如果有其他动画属性(比如opacity),可以单独解构出来,或者只对需要加单位的属性用插值。
内容的提问来源于stack exchange,提问作者Abraham
相关产品推荐
相关产品推荐

