Motion & Framer Motion 动画库 是做什么的?
概述
Motion(前身为 Framer Motion)是一个面向 React 和 JavaScript 的生产级动画库,它让开发者能够以声明式、高性能的方式用最少的代码实现动画效果。它提供了 motion 组件,这些组件为 HTML 元素赋予了动画超能力,支持手势识别(悬停、点击、拖拽、聚焦),并包含布局动画、退出动画和弹性物理效果等高级特性。
何时使用此技能:
- 构建交互式 UI 组件(按钮、卡片、菜单)
- 创建微交互和悬停效果
- 实现页面过渡和路由动画
- 添加基于滚动的动画和视差效果
- 动画化布局变化(大小调整、重新排序、共享元素过渡)
- 拖拽界面
- 复杂动画序列和基于状态的动画
- 用更强大、可控的动画替代 CSS 过渡
技术:
- Motion (v11+) - 来自 Framer Motion 创作者的现代、更精简的库
- Framer Motion - 功能全面的前身(仍被广泛使用)
- 兼容 React 18+,也支持 Vue
- 支持 TypeScript
- 可与 Next.js、Vite、Remix 及所有现代 React 框架一起使用
核心概念
1. Motion 组件
通过在 HTML/SVG 元素前加上 motion. 前缀,将其转换为可动画化的组件:
import { motion } from "framer-motion"
// 普通 HTML 变为 motion 组件
<motion.div />
<motion.button />
<motion.svg />
<motion.path />
每个 motion 组件都接受 animate、initial、transition 等动画属性,以及 whileHover、whileTap 等手势属性。
2. Animate 属性
animate 属性定义了目标动画状态。当值发生变化时,Motion 会自动动画过渡到新状态:
// 简单动画 - x 位置变化
<motion.div animate={{ x: 100 }} />
// 多个属性
<motion.div animate={{ x: 100, opacity: 1, scale: 1.2 }} />
// 状态变化时触发动画
const [isOpen, setIsOpen] = useState(false)
<motion.div animate={{ width: isOpen ? 300 : 100 }} />
3. 初始状态
使用 initial 属性设置动画开始前的初始状态:
<motion.div
initial={{ opacity: 0, y: 50 }}
animate={{ opacity: 1, y: 0 }}
/>
设置 initial={false} 可禁用挂载时的初始动画。
4. 过渡控制
使用 transition 属性控制动画在状态间的移动方式:
// 基于持续时间的过渡
<motion.div
animate={{ x: 100 }}
transition={{ duration: 0.5, ease: "easeInOut" }}
/>
// 弹性物理过渡
<motion.div
animate={{ scale: 1.2 }}
transition={{ type: "spring", stiffness: 300, damping: 20 }}
/>
// 为不同属性设置不同过渡
<motion.div
animate={{ x: 100, opacity: 1 }}
transition={{
x: { type: "spring", stiffness: 300 },
opacity: { duration: 0.2 }
}}
/>
过渡类型:
"tween"(默认)- 基于持续时间的缓动动画"spring"- 基于物理的弹性动画"inertia"- 减速动画(用于拖拽)
5. 动画变体
使用命名变体来组织动画状态,使代码更简洁,并能将状态传递给子组件:
const variants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
exit: { opacity: 0, scale: 0.9 }
}
<motion.div
variants={variants}
initial="hidden"
animate="visible"
exit="exit"
/>
变体传播 - 子组件会自动继承父组件的变体状态:
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: 0.1 // 子动画交错执行
}
}
}
const itemVariants = {
hidden: { x: -20, opacity: 0 },
visible: { x: 0, opacity: 1 }
}
<motion.ul variants={containerVariants} initial="hidden" animate="visible">
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
</motion.ul>
常见模式
1. 悬停动画
使用 whileHover 属性在悬停时触发动画:
// 简单悬停效果
<motion.button
whileHover={{ scale: 1.1 }}
transition={{ duration: 0.2 }}
>
Hover me
</motion.button>
// 多个属性
<motion.div
whileHover={{
scale: 1.05,
backgroundColor: "#f0f0f0",
boxShadow: "0px 10px 30px rgba(0, 0, 0, 0.2)"
}}
>
Hover card
</motion.div>
// 自定义过渡
<motion.button
whileHover={{
scale: 1.2,
transition: { duration: 0.1 } // 手势开始的过渡
}}
transition={{ duration: 0.5 }} // 手势结束的过渡
>
Button
</motion.button>
嵌套元素的悬停效果:
<motion.div whileHover="hover" variants={cardVariants}>
<motion.h3 variants={titleVariants}>Title</motion.h3>
<motion.img variants={imageVariants} />
</motion.div>
2. 点击/按压动画
使用 whileTap 属性在点击或按压时触发动画:
// 点击时缩小
<motion.button
whileTap={{ scale: 0.9 }}
>
Click me
</motion.button>
// 结合悬停和点击
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95, rotate: 3 }}
>
Interactive button
</motion.button>
// 使用变体
const buttonVariants = {
rest: { scale: 1 },
hover: { scale: 1.1 },
pressed: { scale: 0.95 }
}
<motion.button
variants={buttonVariants}
initial="rest"
whileHover="hover"
whileTap="pressed"
>
Button
</motion.button>
3. 拖拽交互
使用 drag 属性使元素可拖拽:
// 基本拖拽(双轴)
<motion.div drag />
// 限制轴
<motion.div drag="x" /> // 仅水平
<motion.div drag="y" /> // 仅垂直
// 拖拽约束
<motion.div
drag
dragConstraints={{ left: -100, right: 100, top: -100, bottom: 100 }}
/>
// 基于父元素的拖拽约束
<motion.div ref={constraintsRef}>
<motion.div drag dragConstraints={constraintsRef} />
</motion.div>
// 拖拽时的视觉反馈
<motion.div
drag
whileDrag={{
scale: 1.1,
boxShadow: "0px 10px 20px rgba(0,0,0,0.2)",
cursor: "grabbing"
}}
dragElastic={0.1} // 超出约束时的弹性
dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }}
/>
拖拽事件:
<motion.div
drag
onDragStart={(event, info) => console.log(info.point)}
onDrag={(event, info) => console.log(info.offset)}
onDragEnd={(event, info) => console.log(info.velocity)}
/>
4. 退出动画(AnimatePresence)
使用 AnimatePresence 在组件从 DOM 中移除时播放动画:
import { AnimatePresence } from "framer-motion"
// 基本退出动画
<AnimatePresence>
{isVisible && (
<motion.div
key="modal"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
)}
</AnimatePresence>
关键要求:
- 组件必须是
<AnimatePresence>的直接子元素 - 必须有一个唯一的
key属性 - 使用
exit属性定义退出动画
带退出动画的列表项:
<AnimatePresence>
{items.map(item => (
<motion.li
key={item.id}
initial={{ opacity: 0, x: -50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 50 }}
layout // 平滑布局变化
>
{item.name}
</motion.li>
))}
</AnimatePresence>
交错的退出动画:
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
when: "beforeChildren",
staggerChildren: 0.1
}
},
exit: {
opacity: 0,
transition: {
when: "afterChildren",
staggerChildren: 0.05,
staggerDirection: -1 // 反向顺序
}
}
}
<AnimatePresence>
{show && (
<motion.div variants={containerVariants} initial="hidden" animate="visible" exit="exit">
<motion.div variants={itemVariants} />
<motion.div variants={itemVariants} />
<motion.div variants={itemVariants} />
</motion.div>
)}
</AnimatePresence>
5. 布局动画
使用 layout 属性自动动画化布局变化(位置、大小):
// 动画化所有布局变化
<motion.div layout />
// 仅动画化位置变化
<motion.div layout="position" />
// 仅动画化大小变化
<motion.div layout="size" />
网格布局动画:
const [columns, setColumns] = useState(3)
<motion.div className="grid">
{items.map(item => (
<motion.div
key={item.id}
layout
transition={{ layout: { duration: 0.3, ease: "easeInOut" } }}
/>
))}
</motion.div>
共享布局动画(layoutId):
使用 layoutId 连接两个不同的元素以实现平滑过渡:
// Tab 指示器示例
<nav>
{tabs.map(tab => (
<button key={tab.id} onClick={() => setActive(tab.id)}>
{tab.label}
{activeTab === tab.id && (
<motion.div
layoutId="underline"
style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 2 }}
/>
)}
</button>
))}
</nav>
// 从缩略图打开模态框
<motion.img
src={thumbnail}
layoutId="product-image"
onClick={() => setExpanded(true)}
/>
<AnimatePresence>
{expanded && (
<motion.div layoutId="product-image">
<img src={fullsize} />
</motion.div>
)}
</AnimatePresence>
6. 基于滚动的动画
使用 whileInView 在元素进入视口时触发动画:
<motion.div
initial={{ opacity: 0, y: 50 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, amount: 0.8 }} // once: 仅触发一次, amount: 80% 可见
transition={{ duration: 0.5 }}
>
滚动到视图中时触发动画
</motion.div>
视口选项:
once: true- 动画仅触发一次amount: 0.5- 元素可见的百分比 (0-1) 或 "some" | "all"margin: "-100px"- 偏移视口边界
交错的滚动动画:
<motion.ul
initial="hidden"
whileInView="visible"
viewport={{ once: true, amount: 0.3 }}
variants={{
visible: {
opacity: 1,
transition: { staggerChildren: 0.1 }
},
hidden: { opacity: 0 }
}}
>
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
</motion.ul>
7. 弹性动画
使用弹性物理效果实现自然、有弹性的动画:
// 基本弹性
<motion.div
animate={{ scale: 1.2 }}
transition={{ type: "spring" }}
/>
// 自定义弹性物理参数
<motion.div
animate={{ x: 100 }}
transition={{
type: "spring",
stiffness: 300, // 越高越快、越干脆(默认: 100)
damping: 20, // 越高弹性越小(默认: 10)
mass: 1, // 越高惯性越大(默认: 1)
}}
/>
// 视觉时长(更简单的弹性控制)
<motion.div
animate={{ rotate: 90 }}
transition={{
type: "spring",
visualDuration: 0.5, // 感知时长
bounce: 0.25 // 弹性程度 (0-1, 默认: 0.25)
}}
/>
弹性预设:
- 柔和 (Gentle):
stiffness: 100, damping: 20 - 摇摆 (Wobbly):
stiffness: 200, damping: 10 - 干脆 (Stiff):
stiffness: 400, damping: 30 - 缓慢 (Slow):
stiffness: 50, damping: 20
手势识别
Motion 提供了声明式的手柄处理程序:
手势属性
<motion.div
whileHover={{ scale: 1.1 }} // 指针悬停在元素上
whileTap={{ scale: 0.9 }} // 主要指针按下元素
whileFocus={{ outline: "2px" }} // 元素获得焦点
whileDrag={{ scale: 1.1 }} // 元素正在被拖拽
whileInView={{ opacity: 1 }} // 元素在视口中
/>
手势事件
<motion.div
onHoverStart={(event, info) => {}}
onHoverEnd={(event, info) => {}}
onTap={(event, info) => {}}
onTapStart={(event, info) => {}}
onTapCancel={(event, info) => {}}
onDragStart={(event, info) => {}}
onDrag={(event, info) => {}}
onDragEnd={(event, info) => {}}
onViewportEnter={(entry) => {}}
onViewportLeave={(entry) => {}}
/>
事件信息对象包含:
point: { x, y }- 页面坐标offset: { x, y }- 从拖拽开始算起的偏移量velocity: { x, y }- 拖拽速度
钩子 (Hooks)
useAnimate
使用 useAnimate 钩子手动控制动画:
import { useAnimate } from "framer-motion"
function Component() {
const [scope, animate] = useAnimate()
useEffect(() => {
// 动画化多个元素
animate([
[scope.current, { opacity: 1 }],
["li", { x: 0, opacity: 1 }, { delay: stagger(0.1) }],
[".button", { scale: 1.2 }]
])
}, [])
return (
<div ref={scope}>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button className="button">Click</button>
</div>
)
}
动画控制:
const controls = animate(element, { x: 100 })
controls.play()
controls.pause()
controls.stop()
controls.speed = 0.5
controls.time = 0 // 跳到开头
useSpring
创建弹性动画的运动值:
import { useSpring } from "framer-motion"
function Component() {
const x = useSpring(0, { stiffness: 300, damping: 20 })
return (
<motion.div style={{ x }}>
<button onClick={() => x.set(100)}>Move</button>
</motion.div>
)
}
useInView
检测元素是否在视口中:
import { useInView } from "framer-motion"
function Component() {
const ref = useRef(null)
const isInView = useInView(ref, { once: true, amount: 0.5 })
return (
<div ref={ref}>
{isInView ? "在视口中!" : "不在视口中"}
</div>
)
}
集成模式
与 GSAP 集成
将 Motion 用于 React 基于状态的动画,使用 GSAP 处理复杂时间线:
import { motion } from "framer-motion"
import gsap from "gsap"
function Component() {
const boxRef = useRef()
const handleClick = () => {
// 使用 GSAP 创建复杂时间线
const tl = gsap.timeline()
tl.to(boxRef.current, { rotation: 360, duration: 1 })
.to(boxRef.current, { scale: 1.5, duration: 0.5 })
.to(boxRef.current, { rotation: 0, scale: 1, duration: 0.8 })
}
return (
<motion.div
ref={boxRef}
whileHover={{ scale: 1.1 }} // 悬停时使用 Motion
animate={{ opacity: 1 }} // 挂载时使用 Motion
initial={{ opacity: 0 }}
>
<button onClick={handleClick}>使用 GSAP 运行动画</button>
</motion.div>
)
}