Motion 系統 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"
// 請勿在同一個專案中混用兩者
Motion Token
// 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 中,將 motion 元件包裹在
"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 Media Query) - 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" />
}