Framer Motion 动画库从入门到高级用法

Sarah Wong | 2026-09-02T01:07:10 | JavaScript, Frontend

全面讲解 Framer Motion 的核心 API,从基础的 motion 组件到 AnimatePresence、布局动画、手势交互和编排复杂动画序列。

# Framer Motion 动画库从入门到高级用法 ## 为什么选 Framer Motion CSS 动画处理简单场景足够,但面对条件动画、退出动画、布局变化动画等复杂场景时就力不从心了。Framer Motion 是 React 生态中最强大的动画库,API 声明式、性能优秀。 ## 安装 ```bash npm install framer-motion ``` ## 基础动画 ```tsx import { motion } from "framer-motion"; function FadeInCard() { return ( Hello Motion ); } ``` ## 退出动画 (AnimatePresence) 这是 Framer Motion 的杀手级特性 — CSS 无法做到的退出动画: ```tsx import { motion, AnimatePresence } from "framer-motion"; function NotificationList({ notifications }) { return ( {notifications.map((n) => ( {n.message} ))} ); } ``` ## Variants(动画变体) 用变体管理复杂的多状态动画: ```tsx const cardVariants = { hidden: { opacity: 0, scale: 0.8 }, visible: { opacity: 1, scale: 1, transition: { duration: 0.5, ease: "easeOut" }, }, hover: { scale: 1.05, boxShadow: "0 10px 30px rgba(0,0,0,0.2)", transition: { duration: 0.2 }, }, tap: { scale: 0.95 }, }; function AnimatedCard({ children }) { return ( {children} ); } ``` ## 交错动画 父子组件协调实现列表交错入场: ```tsx const containerVariants = { hidden: {}, visible: { transition: { staggerChildren: 0.1, delayChildren: 0.2, }, }, }; const itemVariants = { hidden: { opacity: 0, y: 20 }, visible: { opacity: 1, y: 0 }, }; function StaggeredList({ items }) { return ( {items.map((item) => ( {item.text} ))} ); } ``` ## 布局动画 `layout` 属性让元素在位置/大小变化时自动产生平滑过渡: ```tsx function ExpandableCard({ isExpanded, onClick }) { return ( Title {isExpanded && ( Expanded content here... )} ); } ``` ## 滚动触发动画 结合 `useInView` 实现滚动进入视口时触发动画: ```tsx import { motion, useInView } from "framer-motion"; import { useRef } from "react"; function ScrollReveal({ children }) { const ref = useRef(null); const isInView = useInView(ref, { once: true, margin: "-100px" }); return ( {children} ); } ``` ## 性能建议 1. 优先使用 `transform` 和 `opacity` — 这些属性不触发重排 2. 使用 `layoutId` 而非 `layout` 当只需要跨组件动画时 3. 避免同时对大量元素做复杂弹簧动画 4. 用 `will-change: transform` 提示浏览器优化 ## 总结 Framer Motion 的声明式 API 让复杂动画变得优雅可控。AnimatePresence 解决了 React 中退出动画的老大难问题,布局动画让重排变得丝滑。掌握 variants 和 stagger 后,几乎所有 UI 动画需求都能优雅实现。

← Back to Blog