运动系统 v4.2 是做什么的?
面向 React / Next.js 的生产级 UI 动画系统。
专注于性能、可访问性和可用性——而非装饰。
何时使用
在以下情况使用本动画系统:
- 引导注意力(例如,新手引导、关键操作)
- 传达状态(加载、成功、错误、过渡)
- 保持空间连续性(布局变化、导航)
适用场景
- 交互组件(按钮、模态框、菜单)
- 状态切换(加载中 → 加载完成,打开 → 关闭)
- 导航与布局连续性(共享元素、淡入淡出)
注意事项
- 无障碍:始终支持减少动画偏好
- 设备适配:为低端设备调整动画效果
- 性能权衡:优先保证响应性而非视觉流畅度
应避免使用动画的情况
- 纯粹用于装饰
- 降低可用性或清晰度
- 对性能产生负面影响
工作原理
核心原则
动画必须:
- 引导注意力
- 传达状态
- 保持空间连续性
如果不符合上述任何一点,则删除它。
安装
npm install motion
版本
motion/react- 当前 Motion for React 项目的默认路径(包名:motion)framer-motion- 旧版导入路径,适用于仍依赖 Framer Motion 的项目
不要混用。 混用会导致内部调度器冲突和 AnimatePresence 上下文损坏——一个包中的组件无法与另一个包中的组件协调退出动画。
检查项目使用的版本:
cat package.json | grep -E '"motion"|"framer-motion"'
始终从单一来源一致导入:
// 正确(现代)
import { motion, AnimatePresence } from "motion/react"
// 正确(旧版)
import { motion, AnimatePresence } from "framer-motion"
// 切勿在同一个项目中混用
动画令牌
// motionTokens.ts
export const motionTokens = {
duration: {
fast: 0.18,
normal: 0.35,
slow: 0.6
},
// 将这些用作 `transition` 对象内的 `ease` 值:
// transition={{ duration: motionTokens.duration.normal, ease: motionTokens.easing.smooth }}
easing: {
smooth: [0.22, 1, 0.36, 1] as [number, number, number, number],
sharp: [0.4, 0, 0.2, 1] as [number, number, number, number]
},
distance: {
sm: 8,
md: 16,
lg: 24
}
}
使用示例:
import { motionTokens } from "@/lib/motionTokens"
<motion.div
initial={{ opacity: 0, y: motionTokens.distance.md }}
animate={{ opacity: 1, y: 0 }}
transition={{
duration: motionTokens.duration.normal,
ease: motionTokens.easing.smooth
}}
/>
性能规则
安全
- transform
- opacity
避免
- width / height
- top / left
规则:响应性 > 流畅度
设备适配
启发式方法结合了 CPU 核心数和可用内存,以提供更可靠的信号。deviceMemory 在 Chrome/Android 上可用;回退方案涵盖了 Safari 和 Firefox。
const isLowEnd =
typeof navigator !== "undefined" && (
// 内存不足(仅限 Chrome/Android;其他浏览器为 undefined → 视为性能良好)
(navigator.deviceMemory !== undefined && navigator.deviceMemory <= 2) ||
// 核心数少且无内存 API(涵盖在弱硬件上的 Safari/Firefox)
(navigator.deviceMemory === undefined && navigator.hardwareConcurrency <= 4)
)
const duration = isLowEnd ? 0.2 : 0.4
无障碍
JS (useReducedMotion)
import { motion, useReducedMotion } from "motion/react"
export function FadeIn() {
const reduce = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: reduce ? 0 : 24 }}
animate={{ opacity: 1, y: 0 }}
/>
)
}
CSS
@media (prefers-reduced-motion: reduce) {
.motion-safe-transition {
transition: opacity 0.2s;
}
.motion-reduce-transform {
transform: none !important;
}
}
Tailwind
<div class="motion-safe:animate-fade motion-reduce:opacity-100"></div>
架构与模式
核心模式
| 场景 | 模式 |
|---|---|
| 悬停反馈 | whileHover |
| 点击/按压反馈 | whileTap |
| 滚动时显示 | whileInView |
| 滚动绑定值 | useScroll + useTransform |
| 条件挂载/卸载 | AnimatePresence |
| 小型布局变化(单个元素,变化 < ~300px) | layout 属性 |
| 大型布局变化或整页重排 | 避免使用 layout;改用 CSS 过渡或页面级路由 |
| 复杂、命令式动画序列 | useAnimate |
为什么要在大型容器上避免使用
layout? Framer 的布局动画使用transform来协调位置,但在跨越整个视口或触发深度重排的元素上,测量成本会导致明显的卡顿和累积布局偏移 (CLS)。建议改用 CSS Grid/Flexbox 过渡,或仅在特定的子元素上使用layoutId进行协调。
布局与过渡
- 共享元素过渡 →
layoutId(每个挂载的实例必须是唯一的) - 进入/退出过渡 →
AnimatePresence(参见下方的mode指导)
AnimatePresence mode
务必显式指定 mode —— 默认值 ("sync") 同时运行进入和退出动画,这会在大多数 UI 模式中导致视觉重叠。
mode | 何时使用 |
|---|---|
"wait" | 退出完成后才进入。用于模态框、快速提示、页面过渡。 |
"sync" (默认) | 进入和退出重叠。仅在有意重叠时使用(例如,淡入淡出转盘)。 |
"popLayout" | 退出元素立即从布局流中弹出;剩余项目动画填充其位置。用于列表、标签页、可关闭卡片。 |
// 模态框——始终使用 "wait"
<AnimatePresence mode="wait">
{open && <Modal key="modal" />}
</AnimatePresence>
// 可关闭的列表项——使用 "popLayout"
<AnimatePresence mode="popLayout">
{items.map(item => <Card key={item.id} />)}
</AnimatePresence>
高级模式(概念)
- 视差(滚动绑定变换)
- 滚动叙述(粘性区域)
- 3D 倾斜(基于指针的变换)
- 淡入淡出(共享的
layoutId) - 渐进式揭示(clip-path)
- 骨架屏加载(循环透明度)
- 微交互(悬停/点击反馈)
- 弹簧系统(基于物理的动画)
模态框要点
- 焦点陷阱
- Escape 键关闭
- 滚动锁定
- ARIA 角色
- 使用
AnimatePresence mode="wait"以确保退出动画在下一个模态框进入之前完成
完整示例
import React, { useEffect, useRef, useState } from "react"
import { motion, AnimatePresence } from "motion/react"
function useFocusTrap(ref: React.RefObject<HTMLDivElement | null>, active: boolean) {
useEffect(() => {
if (!active || !ref.current) return
const el = ref.current
const focusable = el.querySelectorAll<HTMLElement>(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
)
const first = focusable[0]
const last = focusable[focusable.length - 1]
function handleKey(e: KeyboardEvent) {
if (e.key !== "Tab") return
if (e.shiftKey && document.activeElement === first) {
e.preventDefault()
last?.focus()
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault()
first?.focus()
}
}
el.addEventListener("keydown", handleKey)
first?.focus()
return () => el.removeEventListener("keydown", handleKey)
}, [active, ref])
}
function useScrollLock(active: boolean) {
useEffect(() => {
if (!active) return
const prev = document.body.style.overflow
document.body.style.overflow = "hidden"
return () => { document.body.style.overflow = prev }
}, [active])
}
function Modal({ open, closeModal }: { open: boolean; closeModal: () => void }) {
const ref = useRef<HTMLDivElement>(null)
useFocusTrap(ref, open)
useScrollLock(open)
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") closeModal()
}
if (open) window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [open, closeModal])
return (
// mode="wait" 确保退出动画完成后再进入任何新模态框
<AnimatePresence mode="wait">
{open && (
<motion.div
role="dialog"
aria-modal="true"
aria-labelledby="modal-title"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 flex items-center justify-center bg-black/40"
>
<motion.div
ref={ref}
initial={{ scale: 0.95, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.95, opacity: 0 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
className="bg-white p-6 rounded"
>
<h2 id="modal-title">对话框标题</h2>
<button onClick={closeModal}>关闭</button>
</motion.div>
</motion.div>
)}
</AnimatePresence>
)
}
export function Example() {
const [open, setOpen] = useState(false)
return (
<>
<button onClick={() => setOpen(true)}>打开</button>
<Modal open={open} closeModal={() => setOpen(false)} />
</>
)
}
SSR 安全性
- 匹配服务端和客户端渲染的初始状态
- 避免隐式动画起点(始终显式设置
initial) - 在 Next.js App Router 中,将 motion 组件包裹在
"use client"中
调试
检查:
- 错误的导入(混用
motion/react和framer-motion) - Next.js App Router 中缺少
"use client"指令 AnimatePresence子元素缺少key属性- 水合不匹配(SSR 和客户端的初始状态不同)
- 在大型容器上误用
layout属性导致重排卡顿 - 状态驱动的动画未触发(检查依赖数组)
质量保证
- 无 CLS
- 键盘操作正常
- 模态框中焦点已锁定
- ARIA 角色正确(
role="dialog",aria-modal="true") - 尊重减少动画偏好(
useReducedMotion+ CSS 媒体查询) - Next.js 中无水合警告
- 卸载时动画干净停止(无内存泄漏)
- 所有使用
AnimatePresence的地方显式设置了mode
反模式
- 对布局属性进行动画(
width、height、top、left) - 无目的的无限动画(始终问:这个动画传达了何种状态?)
- 过度交错列表(保持
staggerChildren≤ 0.1s;超过此值会显得缓慢) - 忽略减少动画的偏好设置
- 在大型或全视口容器上使用
layout - 在
AnimatePresence上省略mode(默认"sync"会导致视觉重叠) - 纯粹为了装饰而使用动画
理念
动画即是交互设计。
最终规则
如果动画不能改善用户体验,就删除它。
示例
按钮交互
import { motion } from "motion/react"
export function Button() {
return (
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.97 }}
transition={{ duration: 0.15, ease: [0.4, 0, 0.2, 1] }}
>
点击我
</motion.button>
)
}
减少动画示例
import { motion, useReducedMotion } from "motion/react"
export function FadeIn() {
const reduce = useReducedMotion()
return (
<motion.div
initial={{ opacity: 0, y: reduce ? 0 : 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: reduce ? 0.1 : 0.35, ease: [0.22, 1, 0.36, 1] }}
/>
)
}
交错列表
import { motion } from "motion/react"
const container = {
hidden: {},
visible: {
transition: { staggerChildren: 0.08 } // 保持 ≤ 0.1s 以避免迟缓
}
}
const item = {
hidden: { opacity: 0, y: 10 },
visible: { opacity: 1, y: 0, transition: { duration: 0.3, ease: [0.22, 1, 0.36, 1] } }
}
export function List() {
return (
<motion.ul variants={container} initial="hidden" animate="visible">
{[1, 2, 3].map(i => (
<motion.li key={i} variants={item}>项目 {i}</motion.li>
))}
</motion.ul>
)
}
使用 AnimatePresence 的模态框
import { motion, AnimatePresence } from "motion/react"
export function Modal({ open }: { open: boolean }) {
return (
<AnimatePresence mode="wait">
{open && (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2, ease: [0.22, 1, 0.36, 1] }}
/>
)}
</AnimatePresence>
)
}
滚动视差
import { useScroll, useTransform, motion } from "motion/react"
export function Parallax() {
const { scrollYProgress } = useScroll()
const y = useTransform(scrollYProgress, [0, 1], [0, -80])
return <motion.div style={{ y }} />
}
骨架屏加载
import { motion } from "motion/react"
export function Skeleton() {
return (
<motion.div
className="bg-gray-200 h-6 w-full rounded"
animate={{ opacity: [0.5, 1, 0.5] }}
transition={{
duration: 1.5, // 舒适的脉冲——之前缺失,导致快速闪烁
repeat: Infinity,
ease: "easeInOut"
}}
/>
)
}
共享布局(淡入淡出)
import { motion } from "motion/react"
// layoutId 每个挂载的实例必须是唯一的。
// 如果多个实例可以同时存在,请附加一个唯一 ID:
// layoutId={`shared-${item.id}`}
export function Shared() {
return <motion.div layoutId="shared" />
}