動畫元件庫
概述
此技能提供預先建置的 React 動畫元件庫專業知識,特別是 Magic UI 和 React Bits。這些庫提供生產就緒、具動畫效果的元件,能大幅加速現代互動式網頁應用程式的開發。
Magic UI 提供 150 多個基於 Tailwind CSS 和 Framer Motion 的 TypeScript 元件,專為與 shadcn/ui 無縫整合而設計。元件可複製貼上即用,且高度可自訂。
React Bits 提供 90 多個低依賴的 React 動畫元件,專注於視覺效果、背景和微互動。元件強調效能與易於自訂。
兩個庫皆遵循現代 React 模式,支援 TypeScript,並可與主流設計系統整合。
核心概念
Magic UI 架構
Magic UI 元件建構於三大基礎技術之上:
- Tailwind CSS:工具優先的樣式系統,可透過
tailwind.config.js完全自訂 - Framer Motion:基於物理的動畫與手勢辨識
- shadcn/ui 整合:遵循 shadcn 的 CLI 安裝與元件結構慣例
安裝方式:
# 透過 shadcn CLI(建議)
npx shadcn@latest add https://magicui.design/r/animated-beam
# 手動安裝
# 1. 複製元件程式碼到 components/ui/
# 2. 安裝 motion:npm install motion
# 3. 將所需的 CSS 動畫加入 globals.css
# 4. 確認 lib/utils.ts 中存在 cn() 工具函式
元件結構:
// 所有 Magic UI 元件遵循此模式
import { cn } from "@/lib/utils"
import { motion } from "motion/react"
interface ComponentProps extends React.ComponentPropsWithoutRef<"div"> {
customProp?: string
className?: string
}
export function MagicComponent({ className, customProp, ...props }: ComponentProps) {
return (
<motion.div
className={cn("base-styles", className)}
{...props}
>
{/* 元件內容 */}
</motion.div>
)
}
React Bits 架構
React Bits 強調輕量化、低依賴的獨立元件:
- 自包含:每個元件的外部依賴極少
- CSS-in-JS 可選:許多元件使用內聯樣式或 CSS 模組
- 效能優先:針對 60fps 動畫最佳化
- WebGL 支援:部分元件(Particles、Plasma)使用 WebGL 實現進階效果
安裝:
# 手動複製貼上(主要方式)
# 從 reactbits.dev 複製元件檔案到你的專案
# 關鍵依賴(視需求安裝):
npm install framer-motion # 用於動畫密集型元件
npm install ogl # 用於 WebGL 元件(Particles、Plasma)
元件分類:
- 文字動畫:BlurText、CircularText、CountUp、SpinningText
- 互動元素:MagicButton、Magnet、Dock、Stepper
- 背景效果:Aurora、Plasma、Particles
- 列表與佈局:AnimatedList、Bento Grid
常見模式
1. Magic UI:動態背景模式
使用 SVG 為基礎的模式建立動態背景效果:
import { GridPattern } from "@/components/ui/grid-pattern"
import { AnimatedGridPattern } from "@/components/ui/animated-grid-pattern"
import { cn } from "@/lib/utils"
export default function HeroSection() {
return (
<div className="relative flex h-[500px] w-full items-center justify-center overflow-hidden rounded-lg border">
{/* 靜態網格模式 */}
<GridPattern
squares={[
[4, 4], [5, 1], [8, 2], [5, 3], [10, 10], [12, 15]
]}
className={cn(
"[mask-image:radial-gradient(400px_circle_at_center,white,transparent)]",
"fill-gray-400/30 stroke-gray-400/30"
)}
/>
{/* 動態互動網格 */}
<AnimatedGridPattern
numSquares={50}
maxOpacity={0.5}
duration={4}
repeatDelay={0.5}
className={cn(
"[mask-image:radial-gradient(500px_circle_at_center,white,transparent)]",
"inset-x-0 inset-y-[-30%] h-[200%] skew-y-12"
)}
/>
<h1 className="relative z-10 text-6xl font-bold">
你的內容在此
</h1>
</div>
)
}
2. React Bits:文字揭示動畫
使用 BlurText 實現滾動觸發的文字揭示效果:
import BlurText from './components/BlurText'
export default function MarketingSection() {
return (
<section className="py-20">
{/* 逐詞揭示 */}
<BlurText
text="將你的想法化為現實"
delay={100}
animateBy="words"
direction="top"
className="text-5xl font-bold text-center mb-8"
/>
{/* 逐字揭示,自訂緩動 */}
<BlurText
text="像素級動畫,隨手可得"
delay={50}
animateBy="characters"
direction="bottom"
threshold={0.3}
stepDuration={0.4}
animationFrom={{ filter: 'blur(20px)', opacity: 0, y: 50 }}
animationTo={{ filter: 'blur(0px)', opacity: 1, y: 0 }}
className="text-2xl text-gray-600 text-center"
/>
</section>
)
}
3. Magic UI:按鈕元件與效果
建立帶有閃爍和邊框光束效果的互動按鈕:
import { ShimmerButton } from "@/components/ui/shimmer-button"
import { BorderBeam } from "@/components/ui/border-beam"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
export default function CTASection() {
return (
<div className="flex gap-4 items-center">
{/* 閃爍按鈕 */}
<ShimmerButton
shimmerColor="#ffffff"
shimmerSize="0.05em"
shimmerDuration="3s"
borderRadius="100px"
background="rgba(0, 0, 0, 1)"
className="px-8 py-3"
>
開始使用
</ShimmerButton>
{/* 動畫邊框卡片 */}
<Card className="relative w-[350px] overflow-hidden">
<div className="p-6">
<h3 className="text-2xl font-bold">進階方案</h3>
<p className="text-gray-600">解鎖所有功能</p>
<Button className="mt-4">訂閱</Button>
</div>
<BorderBeam duration={8} size={100} />
</Card>
</div>
)
}
4. React Bits:互動式 Dock 導航
實現帶有放大效果的 macOS 風格 Dock:
import Dock from './components/Dock'
import { VscHome, VscArchive, VscAccount, VscSettingsGear } from 'react-icons/vsc'
import { useNavigate } from 'react-router-dom'
export default function AppNavigation() {
const navigate = useNavigate()
const dockItems = [
{
icon: <VscHome size={24} />,
label: '儀表板',
onClick: () => navigate('/dashboard')
},
{
icon: <VscArchive size={24} />,
label: '專案',
onClick: () => navigate('/projects')
},
{
icon: <VscAccount size={24} />,
label: '個人資料',
onClick: () => navigate('/profile')
},
{
icon: <VscSettingsGear size={24} />,
label: '設定',
onClick: () => navigate('/settings')
}
]
return (
<div className="fixed bottom-4 left-1/2 -translate-x-1/2">
<Dock
items={dockItems}
spring={{ mass: 0.15, stiffness: 200, damping: 15 }}
magnification={80}
distance={250}
panelHeight={70}
baseItemSize={55}
/>
</div>
)
}
5. React Bits:使用 CountUp 的動態統計資料
為儀表板和登陸頁面顯示動畫數字:
import CountUp from './components/CountUp'
export default function Statistics() {
return (
<div className="grid grid-cols-1 md:grid-cols-3 gap-8 py-16">
{/* 收入計數器 */}
<div className="stat-card text-center">
<CountUp
start={0}
end={1000000}
duration={3}
separator=","
prefix="$"
className="text-6xl font-bold text-blue-600"
/>
<p className="text-xl text-gray-600 mt-2">產生的收入</p>
</div>
{/* 正常運作時間百分比 */}
<div className="stat-card text-center">
<CountUp
end={99.9}
duration={2.5}
decimals={1}
suffix="%"
className="text-6xl font-bold text-green-600"
/>
<p className="text-xl text-gray-600 mt-2">正常運作時間</p>
</div>
{/* 客戶數量 */}
<div className="stat-card text-center">
<CountUp
end={10000}
duration={2}
separator=","
className="text-6xl font-bold text-purple-600"
/>
<p className="text-xl text-gray-600 mt-2">滿意客戶</p>
</div>
</div>
)
}
6. Magic UI:用於無限滾動的 Marquee 元件
建立無限滾動的內容展示:
import { Marquee } from "@/components/ui/marquee"
const testimonials = [
{ name: "張三", text: "很棒的產品!", avatar: "/avatar1.jpg" },
{ name: "李四", text: "超出預期", avatar: "/avatar2.jpg" },
{ name: "王五", text: "強烈推薦", avatar: "/avatar3.jpg" }
]
export default function Testimonials() {
return (
<section className="py-20">
<h2 className="text-4xl font-bold text-center mb-12">
客戶評價
</h2>
{/* 水平跑馬燈 */}
<Marquee pauseOnHover className="[--duration:40s]">
{testimonials.map((item, idx) => (
<div key={idx} className="mx-4 w-[350px] rounded-lg border p-6">
<p className="text-lg mb-4">"{item.text}"</p>
<div className="flex items-center gap-3">
<img src={item.avatar} alt={item.name} className="w-10 h-10 rounded-full" />
<p className="font-semibold">{item.name}</p>
</div>
</div>
))}
</Marquee>
{/* 垂直跑馬燈 */}
<Marquee vertical reverse className="h-[400px] mt-8">
{testimonials.map((item, idx) => (
<div key={idx} className="my-4 w-full max-w-md rounded-lg border p-6">
<p>{item.text}</p>
</div>
))}
</Marquee>
</section>
)
}
7. React Bits:WebGL 背景效果
添加高效能的動畫背景:
import Particles from './components/Particles'
import Plasma from './components/Plasma'
import Aurora from './components/Aurora'
// 粒子效果
function ParticlesHero() {
return (
<section style={{ position: 'relative', height: '100vh' }}>
<Particles
particleCount={200}
particleColors={['#FF6B6B', '#4ECDC4', '#45B7D1']}
particleSpread={10}
speed={0.12}
moveParticlesOnHover={true}
particleHoverFactor={2}
particleBaseSize={100}
sizeRandomness={1.2}
alphaParticles={true}
cameraDistance={20}
className="particles-bg"
/>
<div className="relative z-10 flex items-center justify-center h-full">
<h1 className="text-7xl font-bold text-white">
歡迎來到未來
</h1>
</div>
</section>
)
}
// 電漿效果
function PlasmaBackground() {
return (
<div className="relative min-h-screen">
<Plasma
color1="#FF0080"
color2="#7928CA"
color3="#00DFD8"
speed={0.8}
blur={30}
className="plasma-bg"
/>
<div className="relative z-10 p-8">
<h1>帶有電漿背景的內容</h1>
</div>
</div>
)
}
// 極光效果
function AuroraHero() {
return (
<div className="relative min-h-screen">
<Aurora
colors={['#FF00FF', '#00FFFF', '#FFFF00']}
speed={0.5}
blur={80}
/>
<main className="relative z-10">
<h1>賽博龐克極光效果</h1>
</main>
</div>
)
}
整合模式
與 shadcn/ui 整合
Magic UI 元件設計為可與 shadcn/ui 無縫協作:
# 安裝 shadcn/ui 元件
npx shadcn@latest add button card
# 安裝 Magic UI 元件
npx shadcn@latest add https://magicui.design/r/shimmer-button
# 在元件中一起使用
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { ShimmerButton } from "@/components/ui/shimmer-button"
import { BorderBeam } from "@/components/ui/border-beam"
所需工具函式 (lib/utils.ts):
import clsx, { ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
與 Framer Motion 整合
兩個庫皆利用 Framer Motion 實現動畫:
import { motion } from "framer-motion"
import { Magnet } from './components/Magnet'
// 結合 React Bits Magnet 與 Framer Motion 手勢
function InteractiveCard() {
return (
<Magnet magnitude={0.4} maxDistance={180}>
<motion.div
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
className="card p-6 rounded-xl shadow-lg"
>
<h3>互動卡片</h3>
<p>結合金屬吸附與縮放動畫</p>
</motion.div>
</Magnet>
)
}
與 React Router 整合
將動畫元件與路由結合:
import { AnimatePresence, motion } from "framer-motion"
import { useLocation, Routes, Route } from "react-router-dom"
import { Dock } from './components/Dock'
function App() {
const location = useLocation()
return (
<>
{/* 動畫頁面轉場 */}
<AnimatePresence mode="wait">
<Routes location={location} key={location.pathname}>
<Route path="/" element={
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.3 }}
>
<h1>首頁</h1>
</motion.div>
} />
<Route path="/about" element={
<motion.div
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -100 }}
>
<h1>關於我們</h1>
</motion.div>
} />
</Routes>
</AnimatePresence>
{/* 固定底部的導航 Dock */}
<Dock
items={[
{ icon: <HomeIcon />, label: '首頁', onClick: () => navigate('/') },
{ icon: <AboutIcon />, label: '關於', onClick: () => navigate('/about') },
]}
baseItemSize={48}
magnification={60}
/>
</>
)
}
效能考量
Magic UI 最佳實務
- 按需載入元件:僅匯入需要的元件,利用 shadcn CLI 的樹狀搖晃(tree-shaking)特性。
- 限制動畫數量:對於每個頁面元素使用太多
motion.div元件,會導致版面重繪。對於含有多個動畫的大型頁面,應使用will-changeCSS 屬性。 - 避免重新渲染:使用
motion.div搭配layout屬性時,應搭配 React.memo 或使用唯一key值。
React Bits 最佳實務
- WebGL 元件:
Particles、Plasma和Aurora元件使用 WebGL,在行動裝置上應謹慎使用。考慮對移動裝置降低粒子數量或解析度。 - Dock 元件:Dock 元件的彈簧物理模擬在調高
magnification或調低mass值時可能會耗費效能。從較溫和的數值開始調整。 - 文字動畫:
BlurText的每個字元模式在長內容上會比逐詞模式消耗更多資源。優先使用逐詞模式以便內容較長時獲得更好效能。
疑難排解
常見問題
問題:Magic UI 元件出現 TypeScript 錯誤
解決方案:確保你的 tsconfig.json 中的 paths 設定包含 @/* 別名。
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
問題:React Bits WebGL 元件在 Safari 中無法運作
解決方案:Safari 對 WebGL 2 的支援有限。降級使用 WebGL 1 後備方案,或使用非 WebGL 替代方案,例如基於 CSS 的背景效果。
問題:動畫在行動裝置上卡頓
解決方案:
- 降低
Particles中的particleCount值 - 對 Magic UI 動畫使用硬體加速:
className="transform-gpu" - 對非關鍵動畫使用
will-change: transform - 考慮將
framer-motion替換為更輕量的motion套件
問題:shadcn/ui 與 React Bits 的 CSS 衝突
解決方案:React Bits 元件使用內聯樣式,通常不會與 Tailwind 類別衝突。若遇到衝突,可在元件層級使用 !important,或將 React Bits 元件包裹在作用域樣式容器中。
版本相容性
| 庫 | 版本 | React 版本 | 相依性 |
|---|---|---|---|
| Magic UI | 最新 | 18.x, 19.x | motion, tailwind-merge, clsx |
| React Bits | 最新 | 18.x, 19.x | framer-motion(選擇性) |
| shadcn/ui | 最新 | 18.x, 19.x | tailwind-merge, clsx |
| Tailwind CSS | v3.4+ | 不限 | - |
備註:Magic UI 已從
framer-motion遷移至motion套件。使用 v11+ 版本時,請匯入自motion而非framer-motion。React Bits 仍可按需選擇使用framer-motion。