Motion (Framer Motion) — 技能 是做什么的?
名称: motion
目的: 使用 motion/react 在 React 中实现流畅、可访问的动画。
每当需要添加动画、手势或布局过渡时,请使用此技能。
适用场景: 使用 motion/react(motion、AnimatePresence、useScroll 等)时。
不使用场景: 无需动画或组件为纯服务端渲染时。
规则
- 仅限客户端边界: Motion 需要
'use client';尽量保持客户端隔离区小。 - 从简单开始: 在添加弹性物理效果之前,先从不透明度和位移开始。
- 使用正确的工具: 使用
AnimatePresence处理进入/退出,layout用于布局,whileHover/whileTap用于手势。 - 尊重减少动效的偏好: 使用
useReducedMotion()。 - 包体积纪律: 对于较大的动画场景,使用
LazyMotion。
工作流程
- 明确 UX 目的(反馈、过渡、焦点)。
- 添加最小的
'use client'边界。 - 正确实现进入/退出或布局过渡。
- 尊重减少动效的偏好。
- 检查性能和包体积。
检查清单
实现检查清单
-
'use client'仅在需要的地方使用 - 定义了减少动效的行为
-
AnimatePresence包裹条件渲染的 UI - 布局过渡使用
layout
审查检查清单
- 动画不会在每次渲染时重新执行
- Motion 代码不会不必要地扩展客户端树
最小示例
进入/退出
"use client";
import { AnimatePresence, motion } from "motion/react";
export function Toast({
open,
children,
}: {
open: boolean;
children: React.ReactNode;
}) {
return (
<AnimatePresence>
{open ? (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ duration: 0.18 }}
>
{children}
</motion.div>
) : null}
</AnimatePresence>
);
}
布局动画
"use client";
import { motion } from "motion/react";
export function Expander({ open }: { open: boolean }) {
return (
<motion.div layout className="overflow-hidden rounded-md border p-3">
<div className="font-medium">标题</div>
{open ? <div className="mt-2 text-sm">更多内容...</div> : null}
</motion.div>
);
}
减少动效
"use client";
import { motion, useReducedMotion } from "motion/react";
export function FadeIn({ children }: { children: React.ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.div
initial={reduce ? false : { opacity: 0, y: 6 }}
animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0 }}
transition={{ duration: 0.2 }}
>
{children}
</motion.div>
);
}
常见错误/陷阱
- 卸载时未使用
AnimatePresence(退出动画永远不会执行) - 动画布局时未使用
layout - 将 Motion 放置在巨大的客户端树中
- 动画大型列表时未进行虚拟化