Communitygithub.com

React Native Reanimated

在原生 UI 執行緒上執行動畫,繞過 JS Bridge 瓶頸,保持 60fps 流暢度。使用「worklet」小程式在 UI 執行緒透過 JSI 執行,是 React Native 高品質動畫的業界標準。

React Native Reanimated 是什麼?

React Native Reanimated 是一個高效能動畫函式庫,專門解決傳統 React Native 動畫因依賴 JavaScript Bridge 而導致的掉幀問題。其核心技術是「worklet」——這些小型 JavaScript 函式可直接在原生 UI 執行緒上執行,因此即使 JavaScript 執行緒忙碌,動畫依然能維持 60fps 的流暢表現。該技能支援開發者進行手勢驅動的互動(如滑動刪除、拖曳排序、縮放旋轉)、捲動驅動的動畫(如視差頭部、黏貼元素)、佈局動畫(列表項目的進出場效果)以及跨畫面的共享元素轉場。透過 useSharedValue 在 UI 執行緒維護動畫狀態,搭配 useAnimatedStyle 動態計算樣式,並提供 withSpring 與 withTiming 等常見動畫曲線。與 react-native-gesture-handler 深度整合,讓複雜多點觸控手勢得以流暢對應動畫。此外,Layout Animations 支援宣告式定義列表項目的進入與離開效果, scrollEventThrottle 設定為 16 毫秒以確保 60fps 的捲動事件回傳。安裝時需在 babel.config.js 最後一個位置加入 react-native-reanimated/plugin,並注意 worklet 內不能直接存取 JS 端物件。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/TerminalSkills/skills/react-native-reanimated

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

React Native Reanimated 是做什麼的?

概覽

Reanimated 在原生 UI 執行緒上執行動畫——沒有 JS Bridge 瓶頸,不會掉幀。即使 JavaScript 執行緒忙碌,動畫依然能保持 60fps。它使用「worklet」——透過 JSI 在 UI 執行緒上執行的小型 JavaScript 函式。這是 React Native 中生產級動畫的標準:手勢驅動的互動、佈局轉場、基於捲動的效果以及共享元素轉場。

使用時機

  • React Native 中任何超出簡單透明度/變形 (opacity/transform) 的動畫
  • 手勢驅動的互動(滑動刪除、拖曳排序、兩指縮放)
  • 捲動驅動的動畫(視差標頭、黏貼元素)
  • 佈局動畫(項目進入/離開列表)
  • 畫面間的共享元素轉場

使用說明

安裝

npx expo install react-native-reanimated react-native-gesture-handler
// babel.config.js — 加入 Reanimated 插件(必須放在最後)
module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: ["react-native-reanimated/plugin"],  // 必須是最後一個!
  };
};

共享值與動畫樣式

// components/FadeIn.tsx — 使用共享值的基本動畫
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
  withSpring,
} from "react-native-reanimated";
import { useEffect } from "react";

export function FadeInCard({ children }) {
  const opacity = useSharedValue(0);
  const translateY = useSharedValue(20);

  useEffect(() => {
    opacity.value = withTiming(1, { duration: 600 });
    translateY.value = withSpring(0, { damping: 15 });
  }, []);

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
    transform: [{ translateY: translateY.value }],
  }));

  return (
    <Animated.View style={animatedStyle} className="bg-white rounded-xl p-4 shadow-lg">
      {children}
    </Animated.View>
  );
}

手勢動畫

// components/SwipeToDelete.tsx — 搭配動畫的滑動手勢
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withSpring,
  runOnJS,
} from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";

export function SwipeToDelete({ onDelete, children }) {
  const translateX = useSharedValue(0);

  const pan = Gesture.Pan()
    .onUpdate((event) => {
      // 只允許向左滑動
      translateX.value = Math.min(0, event.translationX);
    })
    .onEnd((event) => {
      if (event.translationX < -150) {
        // 滑動距離足夠 — 刪除
        translateX.value = withSpring(-400);
        runOnJS(onDelete)();
      } else {
        // 彈回原位
        translateX.value = withSpring(0);
      }
    });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }],
  }));

  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={animatedStyle}>
        {children}
      </Animated.View>
    </GestureDetector>
  );
}

佈局動畫

// components/AnimatedList.tsx — 項目自動進出場動畫
import Animated, { FadeInDown, FadeOutLeft, LinearTransition } from "react-native-reanimated";

export function AnimatedList({ items, onRemove }) {
  return (
    <Animated.FlatList
      data={items}
      itemLayoutAnimation={LinearTransition}
      renderItem={({ item, index }) => (
        <Animated.View
          entering={FadeInDown.delay(index * 100).springify()}
          exiting={FadeOutLeft.duration(300)}
          className="bg-white p-4 mx-4 my-1 rounded-lg"
        >
          <Text>{item.title}</Text>
          <Pressable onPress={() => onRemove(item.id)}>
            <Text className="text-red-500">移除</Text>
          </Pressable>
        </Animated.View>
      )}
    />
  );
}

捲動驅動的動畫

// components/ParallaxHeader.tsx — 捲動時的視差效果
import Animated, {
  useAnimatedScrollHandler,
  useSharedValue,
  useAnimatedStyle,
  interpolate,
} from "react-native-reanimated";

export function ParallaxHeader() {
  const scrollY = useSharedValue(0);

  const scrollHandler = useAnimatedScrollHandler({
    onScroll: (event) => {
      scrollY.value = event.contentOffset.y;
    },
  });

  const headerStyle = useAnimatedStyle(() => ({
    height: interpolate(scrollY.value, [-100, 0, 200], [400, 300, 100]),
    opacity: interpolate(scrollY.value, [0, 200], [1, 0.3]),
    transform: [
      { translateY: interpolate(scrollY.value, [0, 200], [0, -50]) },
    ],
  }));

  return (
    <>
      <Animated.View style={headerStyle} className="bg-blue-600">
        <Text className="text-white text-3xl font-bold">我的 App</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler} scrollEventThrottle={16}>
        {/* 內容 */}
      </Animated.ScrollView>
    </>
  );
}

範例

範例 1:建立卡片滑動介面

使用者提示:「建立一個類似 Tinder 的卡片滑動介面,動畫要流暢。」

Agent 將會建立一個卡片堆疊,包含平移手勢、根據滑動方向旋轉、彈簧動畫用於彈回,以及卡片移除時的佈局轉場。

範例 2:動畫底部面板

使用者提示:「建立一個可以拖曳向上並吸附到特定位置的底部面板。」

Agent 將會使用帶有吸附點 (snap points) 的平移手勢、用於高度的共享值,以及流暢吸附的彈簧動畫。

準則

  • 使用共享值管理動畫狀態 — useSharedValue 在 UI 執行緒執行
  • 使用 useAnimatedStyle 處理動態樣式 — 在 UI 執行緒重新計算
  • 使用 withSpring 實現自然運動 — 使用 withTiming 實現精確持續時間
  • 使用 runOnJS 從 worklet 呼叫 JS — 必要時橋接到 JS 執行緒
  • Gesture Handler 整合 — Gesture.Pan(), Gesture.Pinch() 等
  • 佈局動畫是宣告式的 — 在 Animated 元件上使用 entering, exiting props
  • 使用 interpolate 進行數值映射 — 將捲動位置映射到透明度、縮放等
  • Babel 插件必須放在最後 — react-native-reanimated/plugin 放在 plugins 陣列的最後
  • 勿在 worklet 中存取 JS 物件 — 只能操作共享值和基本型別
  • scrollEventThrottle={16} — 60fps 的捲動事件,確保動畫流暢

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能