第 2 篇:快速上手 Framer Motion(实操入门)
1. 环境准备
在开始使用 Framer Motion 之前,你需要先确保你的开发环境中已经设置好了 React 项目。我们将使用 Next.js 作为示例,如果你是使用其他 React 框架,步骤也基本相同。
1.1 创建一个 Next.js 项目
如果你还没有创建 Next.js 项目,可以通过以下命令快速创建:
pnpm create next-app my-framer-motion-app
cd my-framer-motion-app
1.2 安装 Framer Motion
在项目根目录下执行以下命令安装 Framer Motion:
pnpm add framer-motion
这样,我们就完成了环境的安装和准备工作。
2. 基础使用:motion.div
和简单动画
在 Framer Motion 中,最常用的做法是将标准的 HTML 元素(如 div
、button
等)替换为 motion
组件,从而使它们具备动画能力。下面我们来实现一个简单的 div
动画。
2.1 创建一个简单的动画
打开你的项目,编辑 pages/index.js
文件,使用 motion.div
创建一个简单的动画:
import { motion } from from 'motion/react';export default function Home() {return (<div className="container"><motion.divinitial={{ opacity: 0 }} // 初始状态:透明度为 0animate={{ opacity: 1 }} // 动画结束状态:透明度为 1transition={{ duration: 1 }} // 动画持续时间为 1 秒className="box">Hello, Framer Motion!</motion.div></div>);
}
2.2 动画解释
initial
: 定义了组件的初始状态,在这里我们让它的透明度为0
。animate
: 定义了组件的目标状态,在这里我们将目标状态设置为透明度1
。transition
: 定义了动画的过渡效果,duration: 1
表示动画持续 1 秒。
你应该能看到一个渐现的效果。
2.3 添加样式
为了更好地展示效果,给 motion.div
添加一些基础样式:
/* styles/globals.css */
.container {display: flex;justify-content: center;align-items: center;height: 100vh;background-color: #f0f0f0;
}.box {width: 200px;height: 200px;background-color: #3498db;display: flex;justify-content: center;align-items: center;color: white;font-size: 20px;border-radius: 10px;
}
现在,当你访问页面时,div
会从完全透明到逐渐显示出来。
3. 交互动画:鼠标悬停与点击
Framer Motion 还提供了便捷的方式来处理用户交互,如鼠标悬停 (whileHover
) 和点击 (whileTap
)。
3.1 鼠标悬停和点击动画
更新你的 motion.div
,添加鼠标悬停和点击时的动画:
<motion.divinitial={{ opacity: 0.5, scale: 0.8 }}animate={{ opacity: 1, scale: 1 }}transition={{ duration: 0.5 }}whileHover={{ scale: 1.1 }} // 鼠标悬停时放大whileTap={{ scale: 0.9 }} // 点击时缩小className="box"
>Hover or Tap Me
</motion.div>
3.2 交互动画解释
whileHover
: 当鼠标悬停在组件上时,动画会触发,元素会放大 1.1 倍。whileTap
: 当组件被点击时,元素会缩小到 0.9 倍。
这些动画让用户与页面交互时有了更生动的反馈。
4. 过渡效果:控制动画时序
Framer Motion 的 transition
属性可以用来精确控制动画的时序和缓动效果。
4.1 设置过渡效果
<motion.divinitial={{ x: -100 }} // 初始状态:x轴偏移 -100pxanimate={{ x: 0 }} // 动画目标状态:x轴偏移 0pxtransition={{duration: 1, // 动画持续时间:1秒ease: "easeInOut" // 缓动效果:easeInOut}}className="box"
>Slide In from Left
</motion.div>
4.2 过渡效果解释
ease
: 设置缓动函数,这里使用easeInOut
,它会让动画既平滑地加速也平滑地减速。duration
: 设置动画的持续时间,单位为秒。
5. 总结
在本篇教程中,我们快速上手了 Framer Motion,完成了以下内容:
- 安装和配置 Framer Motion
- 使用
motion.div
创建简单的动画 - 添加交互效果(悬停与点击)
- 配置过渡效果,控制动画的时序和缓动
这些都是 Framer Motion 中非常基础和常见的用法,掌握了这些,你就可以轻松为 React 应用添加流畅的动画效果。
接下来,我们将在第 3 篇中深入学习如何使用 Variants 来实现复杂的动画效果。敬请期待!