关于 motion-react
介绍如何使用 `motion` 包为 React 界面制作动画的参考技能,涵盖动画、组件进出与布局转场、手势、滚动效果、钩子、包体选项、无障碍支持及常见问题。
主要功能
- 01React 动画组件与属性
- 02关键帧和可复用变体
- 03退出与布局动画
- 04手势、拖动和滚动效果
- 05Motion 值与动画钩子
- 06减少动态效果与包体选项
适用场景
- 01为 React 界面元素添加动画
- 02编排组件进入和退出状态
- 03制作滚动联动或可拖动交互
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ pedronauck/ skills --skill motion-react安装后在 Claude Code 中输入/motion-react确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/animation-api.mdgestures-and-drag.mdhooks-and-motion-values.mdlayout-animations.mdscroll-animations.mdtransitions-api.md详细介绍
Motion for React
Package:motion(原名 framer-motion)。从 "motion/react" 导入。
安装
pnpm add motion
导入
// Standard React (Vite, CRA, Pages Router)
import { motion, AnimatePresence } from "motion/react"
// Next.js App Router — use "motion/react-client" for RSC tree-shaking
"use client"
import * as motion from "motion/react-client"
// Minimal bundle (2.3 KB) — imperative API only
import { useAnimate } from "motion/react-mini"
// Reduced bundle (4.6 KB) — LazyMotion + m component
import { LazyMotion, domAnimation, m } from "motion/react"
Motion 组件
每个 HTML/SVG 元素都有对应的 motion 组件:
<motion.div />
<motion.button />
<motion.svg />
<motion.circle />
自定义组件:使用 motion.create() 封装:
const MotionBox = motion.create(Box)
// forwardRef required — the ref must reach a DOM node
核心动画属性
<motion.div
initial={{ opacity: 0, y: 20 }} // mount state (or false to skip)
animate={{ opacity: 1, y: 0 }} // target state
exit={{ opacity: 0, y: -20 }} // unmount state (needs AnimatePresence)
transition={{ type: "spring", bounce: 0.25 }}
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
whileFocus={{ borderColor: "#00f" }}
whileDrag={{ scale: 1.1 }}
whileInView={{ opacity: 1 }}
viewport={{ once: true, margin: "-100px" }}
/>
可动画值
Motion 可为任何 CSS 值添加动画:opacity、filter、background-image、mask-image。
独立变换(仅用 CSS 无法实现):
- 平移:
x、y、z - 缩放:
scale、scaleX、scaleY - 旋转:
rotate、rotateX、rotateY、rotateZ - 倾斜:
skewX、skewY - 原点:
originX、originY、originZ
值类型:数字、带单位的字符串("100px")、颜色(hex/rgba/hsla)、宽度/高度可用 "auto"。
硬件加速:直接设置 transform 以使用 GPU 合成:
<motion.li
initial={{ transform: "translateX(-100px)" }}
animate={{ transform: "translateX(0px)" }}
transition={{ type: "spring" }}
/>
关键帧
传入数组即可按序列播放动画:
<motion.div animate={{ x: [0, 100, 0] }} />
// null = "use current value"
<motion.div animate={{ x: [null, 100, 0] }} />
变体
用于编排动画的命名动画状态:
const list = {
visible: {
transition: { staggerChildren: 0.1 }
},
hidden: {}
}
const item = {
visible: { opacity: 1, y: 0 },
hidden: { opacity: 0, y: 20 }
}
<motion.ul initial="hidden" animate="visible" variants={list}>
<motion.li variants={item} />
<motion.li variants={item} />
</motion.ul>
变体会沿树向下传递。子元素会从父元素继承 animate/initial/exit。
AnimatePresence — 退出动画
import { AnimatePresence } from "motion/react"
<AnimatePresence>
{isVisible && (
<motion.div
key="modal" // REQUIRED: unique key
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
)}
</AnimatePresence>
关键规则:
- AnimatePresence 必须保持挂载——切勿将它放在条件语句中
- 直接子元素必须具有唯一的
key属性 exit属性仅对 AnimatePresence 内部的motion组件生效
// WRONG — AnimatePresence unmounts with condition
{show && <AnimatePresence><motion.div /></AnimatePresence>}
// CORRECT — condition inside AnimatePresence
<AnimatePresence>{show && <motion.div key="k" />}</AnimatePresence>
模式:"sync"(默认)、"wait"(依次进入/退出)、"popLayout"(将退出元素移出文档流)。
幻灯片模式——更改 key 以触发退出+进入:
<AnimatePresence mode="wait">
<motion.img
key={image.src}
initial={{ x: 300, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
exit={{ x: -300, opacity: 0 }}
/>
</AnimatePresence>
动态退出数据——通过 custom 属性和 usePresenceData 传递:
<AnimatePresence custom={direction}>
<Slide key={id} />
</AnimatePresence>
// Inside Slide:
const direction = usePresenceData()
过渡
完整的过渡 API 详情请参阅 references/transitions-api.md。
快速参考:
// Spring (default for physical props: x, y, scale)
transition={{ type: "spring", bounce: 0.25 }}
transition={{ type: "spring", stiffness: 300, damping: 20 }}
transition={{ type: "spring", visualDuration: 0.5, bounce: 0.25 }}
// Tween (default for opacity, color)
transition={{ duration: 0.3, ease: "easeInOut" }}
// Per-value transitions
transition={{
default: { type: "spring" },
opacity: { duration: 0.2, ease: "linear" }
}}
// Orchestration
transition={{ delay: 0.5, repeat: Infinity, repeatType: "reverse" }}
// Global default
<MotionConfig transition={{ duration: 0.3 }}>
布局动画
完整的布局动画详情请参阅 references/layout-animations.md。
// Auto-animate any layout change
<motion.div layout />
// Shared element transitions
<motion.div layoutId="underline" />
// Customize layout transition
<motion.div layout transition={{ layout: { duration: 0.3 } }} />
手势与拖拽
完整的手势/拖拽 API 请参阅 references/gestures-and-drag.md。
<motion.div
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
drag // enable both axes
drag="x" // constrain to x-axis
dragConstraints={{ left: -100, right: 100 }}
dragElastic={0.2}
/>
滚动动画
完整的滚动 API 请参阅 references/scroll-animations.md。
// Viewport-triggered
<motion.div
initial={{ opacity: 0, y: 50 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
/>
// Scroll-linked progress bar
const { scrollYProgress } = useScroll()
<motion.div style={{ scaleX: scrollYProgress }} />
// Element scroll progress
const ref = useRef(null)
const { scrollYProgress } = useScroll({
target: ref,
offset: ["start end", "end start"]
})
Hooks 与 Motion 值
完整的 Hooks API 请参阅 references/hooks-and-motion-values.md。
// Manual motion values (no re-renders)
const x = useMotionValue(0)
const opacity = useTransform(x, [-200, 0, 200], [0, 1, 0])
<motion.div drag="x" style={{ x, opacity }} />
// Smooth spring following
const springX = useSpring(x, { stiffness: 100, damping: 30 })
// Imperative animation control
const [scope, animate] = useAnimate()
animate("li", { opacity: 1 }, { stagger: 0.1 })
// Event listener (no re-render)
useMotionValueEvent(scrollY, "change", (v) => console.log(v))
包体积优化
| 方案 | 大小 | 包含内容 |
|---|---|---|
motion/react | ~34 KB | 完整 API |
LazyMotion + m | ~4.6 KB | 声明式动画,不含手势 |
motion/react-mini | ~2.3 KB | 仅 useAnimate |
// LazyMotion pattern
import { LazyMotion, domAnimation, m } from "motion/react"
<LazyMotion features={domAnimation}>
<m.div animate={{ opacity: 1 }} />
</LazyMotion>
无障碍
<MotionConfig reducedMotion="user">
<App />
</MotionConfig>
选项:"user"(遵循操作系统设置)、"always"(强制即时切换)、"never"(忽略)。
Hook:当用户偏好减少动态效果时,useReducedMotion() 返回 true。
Tailwind 集成
让每个库发挥所长。移除 Tailwind 的 transition-* 类——它们会产生冲突。
// WRONG — Tailwind transition conflicts with Motion
<motion.div className="transition-all duration-300" animate={{ x: 100 }} />
// CORRECT — Tailwind for styling, Motion for animation
<motion.div className="rounded-lg bg-blue-600 p-4" whileHover={{ scale: 1.05 }} />
Next.js App Router
Motion 组件需要在客户端渲染。使用 "motion/react-client" 以获得最佳的树摇效果:
// components/motion-client.tsx
"use client"
import * as motion from "motion/react-client"
export { motion }
// app/page.tsx (Server Component)
import { motion } from "@/components/motion-client"
<motion.div animate={{ opacity: 1 }} />
常见问题
- 退出动画未触发——AnimatePresence 必须保持挂载;子元素需要唯一的
key - 与 Tailwind 过渡冲突——从 motion 元素中移除
transition-*类 height: "auto"+display: "none"——改用visibility: "hidden"- 可滚动容器中的布局动画——在滚动父元素上添加
layoutScroll属性 - 固定元素中的布局动画——在固定父元素上添加
layoutRoot属性 - 百分比变换 + 布局——转换为像素值;百分比值会导致 FLIP 计算出错
popLayout模式——自定义组件必须使用forwardRef将 ref 转发到 DOM 节点- AnimatePresence
propagate——在嵌套的 AnimatePresence 上设为true,以触发子元素退出动画
References
- Animation API details: references/animation-api.md
- Transition types & spring config: references/transitions-api.md
- Gestures & drag: references/gestures-and-drag.md
- Layout animations: references/layout-animations.md
- Scroll animations: references/scroll-animations.md
- Hooks & motion values: references/hooks-and-motion-values.md