如何在framer-motion中根据props反转动画执行方向?
在Framer Motion中实现动画方向反转
方法一:条件切换初始/目标状态
这是最直接的实现方式,通过isMenuActive的值直接调换initial和animate的背景色状态,让动画自然反向执行。
import { motion } from "framer-motion"; const AnimatedBox = ({ isMenuActive }) => { return ( <motion.div initial={{ backgroundColor: isMenuActive ? "#ff0" : "#000" }} animate={{ backgroundColor: isMenuActive ? "#000" : "#ff0" }} transition={{ duration: 0.5 }} style={{ width: 200, height: 200 }} /> ); }; export default AnimatedBox;
当isMenuActive为true时,动画会从#ff0过渡到#000,刚好是原动画的反向;为false时则执行正常的从黑到黄的过渡。
方法二:使用useAnimation控制器精细控制
如果需要更灵活的动画控制(比如中途反转、结合其他交互),可以用useAnimation钩子创建控制器,调用其reverse()方法实现反转。
import { motion, useAnimation } from "framer-motion"; import { useEffect } from "react"; const AnimatedBox = ({ isMenuActive }) => { const controls = useAnimation(); useEffect(() => { if (isMenuActive) { // 反转动画 controls.reverse(); } else { // 执行正向动画 controls.start({ backgroundColor: "#ff0" }); } }, [isMenuActive, controls]); return ( <motion.div initial={{ backgroundColor: "#000" }} animate={controls} transition={{ duration: 0.5 }} style={{ width: 200, height: 200 }} /> ); }; export default AnimatedBox;
useAnimation的reverse()方法会让当前动画反向播放:如果动画已经完成,会从结束状态倒回到初始状态;如果动画正在播放,则直接反转当前的动画进程。
内容的提问来源于stack exchange,提问作者mikoloism
相关产品推荐
相关产品推荐

