animated-component-libraries

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Animated Component Libraries

动画组件库

Overview

概述

This skill provides expertise in pre-built animated React component libraries, specifically Magic UI and React Bits. These libraries offer production-ready, animated components that significantly accelerate development of modern, interactive web applications.
Magic UI provides 150+ TypeScript components built on Tailwind CSS and Framer Motion, designed for seamless integration with shadcn/ui. Components are copy-paste ready and highly customizable.
React Bits offers 90+ animated React components with minimal dependencies, focusing on visual effects, backgrounds, and micro-interactions. Components emphasize performance and ease of customization.
Both libraries follow modern React patterns, support TypeScript, and integrate with popular design systems.
本技能提供关于预制动画React组件库的专业知识,特别是Magic UI和React Bits。这些库提供了可用于生产环境的动画组件,能显著加速现代交互式Web应用的开发。
Magic UI 提供150+ 基于Tailwind CSS和Framer Motion构建的TypeScript组件,专为与shadcn/ui无缝集成而设计。组件支持直接复制粘贴使用,且高度可定制。
React Bits 提供90+ 低依赖的动画React组件,专注于视觉效果、背景和微交互。组件强调性能和易定制性。
两个库均遵循现代React模式,支持TypeScript,并可与流行设计系统集成。

Core Concepts

核心概念

Magic UI Architecture

Magic UI 架构

Magic UI components are built on three foundational technologies:
  1. Tailwind CSS: Utility-first styling with full customization via
    tailwind.config.js
  2. Framer Motion: Physics-based animations and gesture recognition
  3. shadcn/ui Integration: Follows shadcn conventions for CLI installation and component structure
Installation Methods:
bash
undefined
Magic UI组件基于三项核心技术构建:
  1. Tailwind CSS:实用优先的样式方案,可通过
    tailwind.config.js
    完全定制
  2. Framer Motion:基于物理的动画和手势识别
  3. shadcn/ui 集成:遵循shadcn的CLI安装和组件结构规范
安装方式:
bash
undefined

Via shadcn CLI (recommended)

通过shadcn CLI安装(推荐)

Manual installation

手动安装

1. Copy component code to components/ui/

1. 将组件代码复制到components/ui/

2. Install motion: npm install motion

2. 安装motion依赖:npm install motion

3. Add required CSS animations to globals.css

3. 将所需CSS动画添加到globals.css

4. Ensure cn() utility exists in lib/utils.ts

4. 确保lib/utils.ts中存在cn()工具函数


**Component Structure**:

```typescript
// All Magic UI components follow this pattern:
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}
    >
      {/* Component content */}
    </motion.div>
  )
}

**组件结构**:

```typescript
// 所有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 Architecture

React Bits 架构

React Bits emphasizes lightweight, standalone components with minimal dependencies:
  1. Self-Contained: Each component has minimal external dependencies
  2. CSS-in-JS Optional: Many components use inline styles or CSS modules
  3. Performance-First: Optimized for 60fps animations
  4. WebGL Support: Some components (Particles, Plasma) use WebGL for advanced effects
Installation:
bash
undefined
React Bits强调轻量级、独立的低依赖组件:
  1. 自包含:每个组件的外部依赖极少
  2. 可选CSS-in-JS:许多组件使用内联样式或CSS模块
  3. 性能优先:针对60fps动画进行优化
  4. WebGL支持:部分组件(Particles、Plasma)使用WebGL实现高级效果
安装方式:
bash
undefined

Manual copy-paste (primary method)

主要方式:手动复制粘贴

Copy component files from reactbits.dev to your project

将组件文件从reactbits.dev复制到你的项目中

Key dependencies (install as needed):

关键依赖(按需安装):

npm install framer-motion # For animation-heavy components npm install ogl # For WebGL components (Particles, Plasma)

**Component Categories**:

- **Text Animations**: BlurText, CircularText, CountUp, SpinningText
- **Interactive Elements**: MagicButton, Magnet, Dock, Stepper
- **Backgrounds**: Aurora, Plasma, Particles
- **Lists & Layouts**: AnimatedList, Bento Grid
npm install framer-motion # 用于动画密集型组件 npm install ogl # 用于WebGL组件(Particles、Plasma)

**组件分类**:

- **文本动画**:BlurText、CircularText、CountUp、SpinningText
- **交互元素**:MagicButton、Magnet、Dock、Stepper
- **背景效果**:Aurora、Plasma、Particles
- **列表与布局**:AnimatedList、Bento Grid

Common Patterns

常见模式

1. Magic UI: Animated Background Patterns

1. Magic UI:动画背景图案

Create dynamic background effects with SVG-based patterns:
typescript
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">
      {/* Static Grid Pattern */}
      <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"
        )}
      />

      {/* Animated Interactive Grid */}
      <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">
        Your Content Here
      </h1>
    </div>
  )
}
使用基于SVG的图案创建动态背景效果:
typescript
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: Text Reveal Animations

2. React Bits:文本渐显动画

Implement scroll-triggered text reveals with BlurText:
jsx
import BlurText from './components/BlurText'

export default function MarketingSection() {
  return (
    <section className="py-20">
      {/* Word-by-word reveal */}
      <BlurText
        text="Transform your ideas into reality"
        delay={100}
        animateBy="words"
        direction="top"
        className="text-5xl font-bold text-center mb-8"
      />

      {/* Character-by-character reveal with custom easing */}
      <BlurText
        text="Pixel-perfect animations at your fingertips"
        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>
  )
}
使用BlurText实现滚动触发的文本渐显效果:
jsx
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: Button Components with Effects

3. Magic UI:带特效的按钮组件

Create interactive buttons with shimmer and border beam effects:
typescript
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">
      {/* Shimmer Button */}
      <ShimmerButton
        shimmerColor="#ffffff"
        shimmerSize="0.05em"
        shimmerDuration="3s"
        borderRadius="100px"
        background="rgba(0, 0, 0, 1)"
        className="px-8 py-3"
      >
        Get Started
      </ShimmerButton>

      {/* Card with Animated Border */}
      <Card className="relative w-[350px] overflow-hidden">
        <div className="p-6">
          <h3 className="text-2xl font-bold">Premium Plan</h3>
          <p className="text-gray-600">Unlock all features</p>
          <Button className="mt-4">Subscribe</Button>
        </div>
        <BorderBeam duration={8} size={100} />
      </Card>
    </div>
  )
}
创建带有闪光和边框光束效果的交互式按钮:
typescript
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: Interactive Dock Navigation

4. React Bits:交互式停靠导航栏

Implement macOS-style dock with magnification effects:
jsx
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: 'Dashboard',
      onClick: () => navigate('/dashboard')
    },
    {
      icon: <VscArchive size={24} />,
      label: 'Projects',
      onClick: () => navigate('/projects')
    },
    {
      icon: <VscAccount size={24} />,
      label: 'Profile',
      onClick: () => navigate('/profile')
    },
    {
      icon: <VscSettingsGear size={24} />,
      label: 'Settings',
      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>
  )
}
实现类似macOS的带有放大效果的停靠栏:
jsx
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: Animated Statistics with CountUp

5. React Bits:带数字动画的统计组件

Display animated numbers for dashboards and landing pages:
jsx
import CountUp from './components/CountUp'

export default function Statistics() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-8 py-16">
      {/* Revenue Counter */}
      <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">Revenue Generated</p>
      </div>

      {/* Uptime Percentage */}
      <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">Uptime</p>
      </div>

      {/* Customer Count */}
      <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">Happy Customers</p>
      </div>
    </div>
  )
}
为仪表盘和着陆页实现数字动画效果:
jsx
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 Component for Infinite Scroll

6. Magic UI:无限滚动的跑马灯组件

Create infinite scrolling content displays:
typescript
import { Marquee } from "@/components/ui/marquee"

const testimonials = [
  { name: "John Doe", text: "Amazing product!", avatar: "/avatar1.jpg" },
  { name: "Jane Smith", text: "Exceeded expectations", avatar: "/avatar2.jpg" },
  { name: "Bob Johnson", text: "Highly recommend", avatar: "/avatar3.jpg" }
]

export default function Testimonials() {
  return (
    <section className="py-20">
      <h2 className="text-4xl font-bold text-center mb-12">
        What Our Customers Say
      </h2>

      {/* Horizontal Marquee */}
      <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>

      {/* Vertical 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>
  )
}
创建无限滚动的内容展示:
typescript
import { Marquee } from "@/components/ui/marquee"

const testimonials = [
  { name: "John Doe", text: "很棒的产品!", avatar: "/avatar1.jpg" },
  { name: "Jane Smith", text: "超出预期", avatar: "/avatar2.jpg" },
  { name: "Bob Johnson", 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 Background Effects

7. React Bits:WebGL背景效果

Add high-performance animated backgrounds:
jsx
import Particles from './components/Particles'
import Plasma from './components/Plasma'
import Aurora from './components/Aurora'

// Particles Effect
export default 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">
          Welcome to the Future
        </h1>
      </div>
    </section>
  )
}

// Plasma Effect
export default 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>Content with Plasma Background</h1>
      </div>
    </div>
  )
}

// Aurora Effect
export default 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>Cyberpunk Aurora Effect</h1>
      </main>
    </div>
  )
}
添加高性能动画背景:
jsx
import Particles from './components/Particles'
import Plasma from './components/Plasma'
import Aurora from './components/Aurora'

// 粒子效果
export default 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>
  )
}

// 等离子效果
export default 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>
  )
}

// 极光效果
export default 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>
  )
}

Integration Patterns

集成模式

Integration with shadcn/ui

与shadcn/ui集成

Magic UI components are designed to work seamlessly with shadcn/ui:
bash
undefined
Magic UI组件专为与shadcn/ui无缝协作而设计:
bash
undefined

Install shadcn/ui component

安装shadcn/ui组件

npx shadcn@latest add button card
npx shadcn@latest add button card

Install Magic UI component

安装Magic UI组件

Use together in components

在组件中一起使用

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"

**Utility Function Required** (`lib/utils.ts`):

```typescript
import clsx, { ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}
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`):

```typescript
import clsx, { ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

Integration with Framer Motion

与Framer Motion集成

Both libraries leverage Framer Motion for animations:
jsx
import { motion } from "framer-motion"
import { Magnet } from './components/Magnet'

// Combine React Bits Magnet with Framer Motion gestures
export default 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>Interactive Card</h3>
        <p>Combines magnetic pull with scale animation</p>
      </motion.div>
    </Magnet>
  )
}
两个库均借助Framer Motion实现动画:
jsx
import { motion } from "framer-motion"
import { Magnet } from './components/Magnet'

// 将React Bits的Magnet组件与Framer Motion手势结合使用
export default 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>
  )
}

Integration with React Router

与React Router集成

Combine animated components with routing:
jsx
import { AnimatePresence, motion } from "framer-motion"
import { useLocation, Routes, Route } from "react-router-dom"
import { Dock } from './components/Dock'

export default function App() {
  const location = useLocation()

  return (
    <>
      {/* Animated Page Transitions */}
      <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 }}
            >
              <HomePage />
            </motion.div>
          } />
        </Routes>
      </AnimatePresence>

      {/* Persistent Dock Navigation */}
      <Dock items={navItems} />
    </>
  )
}
将动画组件与路由结合:
jsx
import { AnimatePresence, motion } from "framer-motion"
import { useLocation, Routes, Route } from "react-router-dom"
import { Dock } from './components/Dock'

export default 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 }}
            >
              <HomePage />
            </motion.div>
          } />
        </Routes>
      </AnimatePresence>

      {/* 持久化停靠导航栏 */}
      <Dock items={navItems} />
    </>
  )
}

Combining Magic UI and React Bits

结合Magic UI和React Bits

Leverage strengths of both libraries in a single project:
jsx
// Magic UI: Patterns and structural components
import { GridPattern } from "@/components/ui/grid-pattern"
import { BorderBeam } from "@/components/ui/border-beam"
import { Marquee } from "@/components/ui/marquee"

// React Bits: Interactive elements and effects
import BlurText from './components/BlurText'
import CountUp from './components/CountUp'
import Particles from './components/Particles'

export default function LandingPage() {
  return (
    <main>
      {/* Hero with React Bits background + Magic UI pattern */}
      <section className="relative h-screen">
        <Particles particleCount={150} />
        <GridPattern
          squares={[[4,4], [8,2], [12,6]]}
          className="opacity-30"
        />
        <BlurText
          text="Next-Generation Platform"
          className="text-7xl font-bold"
        />
      </section>

      {/* Stats with React Bits CountUp */}
      <section>
        <CountUp end={10000} suffix="+" />
      </section>

      {/* Testimonials with Magic UI Marquee */}
      <section>
        <Marquee>
          {/* Testimonial cards */}
        </Marquee>
      </section>
    </main>
  )
}
在单个项目中利用两个库的优势:
jsx
// Magic UI:图案和结构性组件
import { GridPattern } from "@/components/ui/grid-pattern"
import { BorderBeam } from "@/components/ui/border-beam"
import { Marquee } from "@/components/ui/marquee"

// React Bits:交互元素和特效
import BlurText from './components/BlurText'
import CountUp from './components/CountUp'
import Particles from './components/Particles'

export default function LandingPage() {
  return (
    <main>
      {/* 带有React Bits背景和Magic UI图案的英雄区 */}
      <section className="relative h-screen">
        <Particles particleCount={150} />
        <GridPattern
          squares={[[4,4], [8,2], [12,6]]}
          className="opacity-30"
        />
        <BlurText
          text="下一代平台"
          className="text-7xl font-bold"
        />
      </section>

      {/* 带有React Bits CountUp的统计区 */}
      <section>
        <CountUp end={10000} suffix="+" />
      </section>

      {/* 带有Magic UI跑马灯的评价区 */}
      <section>
        <Marquee>
          {/* 评价卡片 */}
        </Marquee>
      </section>
    </main>
  )
}

Performance Optimization

性能优化

Magic UI Performance Tips

Magic UI性能优化技巧

  1. Use CSS Masks Instead of Clipping: More performant for large patterns
typescript
<GridPattern
  className="[mask-image:radial-gradient(400px_circle_at_center,white,transparent)]"
/>
  1. Reduce Animation Complexity: Lower
    numSquares
    for AnimatedGridPattern on mobile
typescript
const isMobile = window.innerWidth < 768
<AnimatedGridPattern
  numSquares={isMobile ? 20 : 50}
  duration={isMobile ? 6 : 4}
/>
  1. Lazy Load Components: Use React.lazy for heavy components
typescript
const AnimatedGridPattern = React.lazy(() =>
  import("@/components/ui/animated-grid-pattern")
)
  1. 使用CSS遮罩而非裁剪:对于大型图案,性能更优
typescript
<GridPattern
  className="[mask-image:radial-gradient(400px_circle_at_center,white,transparent)]"
/>
  1. 降低动画复杂度:在移动端减少AnimatedGridPattern的
    numSquares
    数量
typescript
const isMobile = window.innerWidth < 768
<AnimatedGridPattern
  numSquares={isMobile ? 20 : 50}
  duration={isMobile ? 6 : 4}
/>
  1. 懒加载组件:对重型组件使用React.lazy
typescript
const AnimatedGridPattern = React.lazy(() =>
  import("@/components/ui/animated-grid-pattern")
)

React Bits Performance Tips

React Bits性能优化技巧

  1. WebGL Components: Reduce particle count on low-end devices
jsx
const particleCount = navigator.hardwareConcurrency > 4 ? 300 : 150

<Particles
  particleCount={particleCount}
  speed={0.1}
/>
  1. Disable Animations on Reduced Motion:
jsx
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches

<BlurText
  text="Accessible text"
  delay={prefersReducedMotion ? 0 : 100}
  animateBy={prefersReducedMotion ? "none" : "words"}
/>
  1. Optimize Marquee Content: Limit items for better performance
typescript
<Marquee repeat={2}> {/* Instead of default 4 */}
  {items.slice(0, 10)} {/* Limit items */}
</Marquee>
  1. Use RequestIdleCallback for Non-Critical Animations:
jsx
useEffect(() => {
  if ('requestIdleCallback' in window) {
    requestIdleCallback(() => {
      // Initialize expensive animations
    })
  }
}, [])
  1. WebGL组件:在低端设备上减少粒子数量
jsx
const particleCount = navigator.hardwareConcurrency > 4 ? 300 : 150

<Particles
  particleCount={particleCount}
  speed={0.1}
/>
  1. 在精简动效模式下禁用动画:
jsx
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches

<BlurText
  text="无障碍文本"
  delay={prefersReducedMotion ? 0 : 100}
  animateBy={prefersReducedMotion ? "none" : "words"}
/>
  1. 优化跑马灯内容:限制项目数量以提升性能
typescript
<Marquee repeat={2}> {/* 替代默认的4次 */}
  {items.slice(0, 10)} {/* 限制项目数量 */}
</Marquee>
  1. 对非关键动画使用RequestIdleCallback:
jsx
useEffect(() => {
  if ('requestIdleCallback' in window) {
    requestIdleCallback(() => {
      // 初始化重型动画
    })
  }
}, [])

Common Pitfalls

常见问题

1. Missing Dependencies

1. 依赖缺失

Problem: Component breaks due to missing
motion
or utility functions.
Solution: Always install required dependencies and utilities:
bash
undefined
问题:组件因缺少
motion
或工具函数而无法运行。
解决方案:始终安装所需依赖和工具函数:
bash
undefined

Magic UI requirements

Magic UI所需依赖

npm install motion clsx tailwind-merge
npm install motion clsx tailwind-merge

React Bits WebGL components

React Bits WebGL组件所需依赖

npm install ogl
npm install ogl

Ensure cn() utility exists

确保存在cn()工具函数


```typescript
// lib/utils.ts
import clsx, { ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

```typescript
// lib/utils.ts
import clsx, { ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

2. CSS Animations Not Applied

2. CSS动画未生效

Problem: Magic UI animations don't work after manual installation.
Solution: Add required CSS animations to
globals.css
:
css
/* app/globals.css */
@theme inline {
  --animate-ripple: ripple var(--duration, 2s) ease calc(var(--i, 0) * 0.2s) infinite;
  --animate-shimmer-slide: shimmer-slide var(--speed) ease-in-out infinite alternate;
  --animate-marquee: marquee var(--duration) linear infinite;
  --animate-marquee-vertical: marquee-vertical var(--duration) linear infinite;
}

@keyframes ripple {
  0%, 100% { transform: translate(-50%, -50%) scale(1); }
  50% { transform: translate(-50%, -50%) scale(0.9); }
}

@keyframes shimmer-slide {
  to { transform: translate(calc(100cqw - 100%), 0); }
}

@keyframes marquee {
  from { transform: translateX(0); }
  to { transform: translateX(calc(-100% - var(--gap))); }
}

@keyframes marquee-vertical {
  from { transform: translateY(0); }
  to { transform: translateY(calc(-100% - var(--gap))); }
}
问题:手动安装后Magic UI动画无法工作。
解决方案:将所需CSS动画添加到
globals.css
:
css
/* app/globals.css */
@theme inline {
  --animate-ripple: ripple var(--duration, 2s) ease calc(var(--i, 0) * 0.2s) infinite;
  --animate-shimmer-slide: shimmer-slide var(--speed) ease-in-out infinite alternate;
  --animate-marquee: marquee var(--duration) linear infinite;
  --animate-marquee-vertical: marquee-vertical var(--duration) linear infinite;
}

@keyframes ripple {
  0%, 100% { transform: translate(-50%, -50%) scale(1); }
  50% { transform: translate(-50%, -50%) scale(0.9); }
}

@keyframes shimmer-slide {
  to { transform: translate(calc(100cqw - 100%), 0); }
}

@keyframes marquee {
  from { transform: translateX(0); }
  to { transform: translateX(calc(-100% - var(--gap))); }
}

@keyframes marquee-vertical {
  from { transform: translateY(0); }
  to { transform: translateY(calc(-100% - var(--gap))); }
}

3. Z-Index Conflicts

3. Z-Index冲突

Problem: Background patterns or effects cover foreground content.
Solution: Use proper z-index layering:
jsx
<div className="relative">
  {/* Background (z-0 or negative) */}
  <GridPattern className="absolute inset-0 -z-10" />

  {/* Content (higher z-index) */}
  <div className="relative z-10">
    <h1>Content appears above pattern</h1>
  </div>
</div>
问题:背景图案或特效覆盖了前景内容。
解决方案:使用正确的z-index层级:
jsx
<div className="relative">
  {/* 背景(z-0或负值) */}
  <GridPattern className="absolute inset-0 -z-10" />

  {/* 内容(更高的z-index) */}
  <div className="relative z-10">
    <h1>内容显示在图案上方</h1>
  </div>
</div>

4. Performance Issues with Multiple Animated Components

4. 多个动画组件导致性能问题

Problem: Page lags when multiple heavy animations run simultaneously.
Solution: Implement progressive enhancement and conditional rendering:
jsx
import { useState, useEffect } from 'react'

export default function OptimizedPage() {
  const [enableHeavyEffects, setEnableHeavyEffects] = useState(false)

  useEffect(() => {
    // Check device capability
    const isHighEnd = navigator.hardwareConcurrency > 4 &&
                     !navigator.userAgent.includes('Mobile')
    setEnableHeavyEffects(isHighEnd)
  }, [])

  return (
    <section className="relative">
      {enableHeavyEffects ? (
        <Particles particleCount={300} />
      ) : (
        <GridPattern /> {/* Lighter alternative */}
      )}

      <div className="content">
        {/* Page content */}
      </div>
    </section>
  )
}
问题:当多个重型动画同时运行时,页面出现卡顿。
解决方案:实现渐进增强和条件渲染:
jsx
import { useState, useEffect } from 'react'

export default function OptimizedPage() {
  const [enableHeavyEffects, setEnableHeavyEffects] = useState(false)

  useEffect(() => {
    // 检查设备性能
    const isHighEnd = navigator.hardwareConcurrency > 4 &&
                     !navigator.userAgent.includes('Mobile')
    setEnableHeavyEffects(isHighEnd)
  }, [])

  return (
    <section className="relative">
      {enableHeavyEffects ? (
        <Particles particleCount={300} />
      ) : (
        <GridPattern /> {/* 更轻量的替代方案 */}
      )}

      <div className="content">
        {/* 页面内容 */}
      </div>
    </section>
  )
}

5. TypeScript Type Errors

5. TypeScript类型错误

Problem: TypeScript complains about component props.
Solution: Extend proper base types:
typescript
// Magic UI pattern
interface CustomComponentProps extends React.ComponentPropsWithoutRef<"div"> {
  customProp?: string
  className?: string
}

// React Bits pattern
interface CustomProps extends React.HTMLAttributes<HTMLDivElement> {
  customProp?: string
}
问题:TypeScript对组件props报错。
解决方案:扩展正确的基础类型:
typescript
// Magic UI模式
interface CustomComponentProps extends React.ComponentPropsWithoutRef<"div"> {
  customProp?: string
  className?: string
}

// React Bits模式
interface CustomProps extends React.HTMLAttributes<HTMLDivElement> {
  customProp?: string
}

6. Tailwind Classes Not Applied

6. Tailwind类未生效

Problem: Custom Tailwind classes in Magic UI components don't work.
Solution: Ensure content paths include component directory:
javascript
// tailwind.config.js
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}", // Include components directory
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
问题:Magic UI组件中的自定义Tailwind类无法生效。
解决方案:确保内容路径包含组件目录:
javascript
// tailwind.config.js
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}", // 包含组件目录
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Resources

资源

Official Documentation

官方文档

Key Scripts

关键脚本

  • scripts/component_importer.py
    - Import and customize components from both libraries
  • scripts/props_generator.py
    - Generate component prop configurations
  • scripts/component_importer.py
    - 从两个库中导入并定制组件
  • scripts/props_generator.py
    - 生成组件props配置

References

参考资料

  • references/magic_ui_components.md
    - Complete Magic UI component catalog with usage examples
  • references/react_bits_components.md
    - React Bits component library reference
  • references/customization_guide.md
    - Prop-based customization patterns for both libraries
  • references/magic_ui_components.md
    - 完整的Magic UI组件目录及使用示例
  • references/react_bits_components.md
    - React Bits组件库参考
  • references/customization_guide.md
    - 基于props的两个库定制模式

Starter Assets

入门资源

  • assets/component_showcase/
    - Interactive demo of all components
  • assets/examples/
    - Landing page sections, dashboard widgets, micro-interactions
  • assets/component_showcase/
    - 所有组件的交互式演示
  • assets/examples/
    - 着陆页区块、仪表盘部件、微交互示例

Related Skills

相关技能

  • motion-framer: For understanding underlying animation concepts used by both libraries
  • gsap-scrolltrigger: Alternative approach for scroll-driven animations
  • react-spring-physics: Alternative physics-based animation library
  • threejs-webgl: For 3D background effects as alternative to Particles/Plasma
  • motion-framer: 用于理解两个库所使用的底层动画概念
  • gsap-scrolltrigger: 滚动驱动动画的替代方案
  • react-spring-physics: 基于物理的动画库替代方案
  • threejs-webgl: 用于3D背景效果,可替代Particles/Plasma组件