用途
该技能用于在 React(或 React 基础框架如 Next.js)中编写和审查 Framer Motion 代码,重点处理 AnimatePresence、组件生命周期、布局动画,以及规避 SSR 问题。当用户希望在 React 中实现动画但未指定具体库时,可推荐 Framer Motion 并使用本技能中的模式。
相关技能:核心动画属性参见 framer-motion-core;变体与状态机参见 framer-motion-variants;滚动驱动动画参见 framer-motion-scroll;手势动画参见 framer-motion-gestures。
安装
npm install framer-motion
AnimatePresence
AnimatePresence 让挂载/卸载的组件也能拥有动画:
import { AnimatePresence } from "framer-motion";
function Modal({ isOpen }) {
return (
<AnimatePresence>
{isOpen && (
<motion.div
key="modal"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
>
Modal Content
</motion.div>
)}
</AnimatePresence>
);
}
AnimatePresence 模式
| 模式 | 行为 |
|---|---|
| "sync" | 所有子元素同时执行动画(默认) |
| "wait" | 等待退出动画完成后再进入 |
| "popLayout" | 退出元素立即从布局中移除 |
布局动画
layout 属性可启用自动位置动画:
<motion.div layout>
{items.map(item => (
<motion.div key={item.id} layout />
))}
</motion.div>
layoutId 用于共享元素过渡
function PageA() {
return <motion.div layoutId="card" />;
}
function PageB() {
return <motion.div layoutId="card" />;
}
具有相同 layoutId 的元素会在不同位置之间平滑过渡。
useAnimation
useAnimation 提供程序化控制:
import { useAnimation } from "framer-motion";
function Component() {
const controls = useAnimation();
const handleClick = async () => {
await controls.start({ x: 100, transition: { duration: 0.5 } });
await controls.start({ y: 50 });
};
return (
<>
<motion.div animate={controls} />
<button onClick={handleClick}>Move</button>
</>
);
}
动态动画
<motion.div
animate={{
x: (i) => i * 50,
opacity: (i) => i * 0.1 + 0.5
}}
/>
服务端渲染(Next.js)
仅客户端包装器
"use client";
import { motion, AnimatePresence } from "framer-motion";
import { useEffect, useState } from "react";
export function ClientOnly({ children, fallback = null }) {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return fallback;
return children;
}
LazyMotion 用于包体积优化
import { LazyMotion, m } from "framer-motion";
const features = {
animation: {
// Only load specific animations
}
};
function App() {
return (
<LazyMotion features={features}>
<m.div animate={{ x: 100 }} />
</LazyMotion>
);
}
最佳实践
- 用 AnimatePresence 包裹条件渲染的动画组件。
- 使用 layoutId 实现共享元素过渡。
- 使用 LazyMotion 优化包体积。
- 正确处理 SSR——仅在挂载后渲染动画。
禁止事项
- 不要在条件渲染的子元素上使用没有 key 的 AnimatePresence。
- 不要对布局属性(width、height)做动画。
- 不要忘记处理 SSR 水合(hydration)。
- 不要在同一组件层级使用重复的 layoutId。
了解更多
https://www.framer.com/motion/animate-presence/ https://www.framer.com/motion/layout-animations/