动效系统 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 prop |
| 较大的布局偏移或全页面重排 | 避免 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 中,用
"use client"包裹动效组件
调试
检查:
- 错误的导入(混用
motion/react和framer-motion) - 缺少 Next.js App Router 中的
"use client"指令 AnimatePresence子节点缺少keyprop- 水合不匹配(SSR 和客户端初始状态不同)
- 在大容器上误用
layoutprop 导致重排抖动 - 状态驱动的动画未触发(检查依赖数组)
质量检查
- 无 CLS
- 键盘可用
- 弹窗中焦点已捕获
- ARIA 角色正确(
role="dialog"、aria-modal="true") - 减少动效偏好已尊重(
useReducedMotion+ CSS 媒体查询) - Next.js 中无水合警告
- 卸载时动画干净停止(无内存泄漏)
- 所有使用
AnimatePresence的地方都明确设置了mode
反模式
- 动画化布局属性(
width、height、top、left) - 无目的的无限动画(始终问:这传达了何种状态?)
- 过度错开列表(保持
staggerChildren≤ 0.1 秒;超过则感觉缓慢) - 忽略减少动效偏好
- 在大型或全视口容器上使用
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.1 秒以避免迟钝感
}
}
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" />
}