Communitygithub.com

TerminalSkills/skills

React Native Reanimated 是一個動畫函式庫,透過 worklet 和 shared value 在 UI 執行緒上執行動畫,因此即使在 JavaScript 執行緒忙碌時,動畫依然保持流暢。適用於「在 React Native 中製作動畫」、「Reanimated」、「流暢的行動動畫」、「手勢動畫」、「共享元素過渡」、「60fps React Native 動畫」,或從 Reanimated 3 升級到 4 的情境。涵蓋 Reanimated 4:worklet、shared value、佈局動畫、CSS 過渡、手勢和滾動驅動動畫。

skills 是什麼?

React Native Reanimated 是一個高效能的動畫函式庫,它利用 worklet 和 shared value 將動畫執行從 JavaScript 執行緒移至原生 UI 執行緒,確保動畫即使在 JS 執行緒繁忙時也能達到 60fps 或顯示器更新率。這個技能專注於 Reanimated 4(4.7.0),該版本僅適用於新架構,並將 worklet 功能移至獨立的 `react-native-worklets` 套件,同時新增 CSS 風格的過渡和動畫。它支援手勢驅動的互動(例如滑動刪除、拖曳重新排序、縮放)、佈局動畫(列表項目的進入/離開)、滾動驅動效果(視差標題)以及仍處於實驗階段的共享元素過渡。使用者應根據目標平台(Expo 或 React Native Community CLI)進行設置,並遵循嚴格的 Babel 配置規則,且需注意與舊版架構的不相容性。

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

在你喜歡的 AI 中提問

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

說明文件

React Native Reanimated

概述

Reanimated 在原生 UI 執行緒上執行動畫,因此即使在 JavaScript 執行緒忙碌時,動畫也能維持 60fps(或顯示器的更新率)。它使用「worklet」:透過 JSI 在 UI 執行緒上執行的小型 JavaScript 函式。這是 React Native 中生產級動畫的標準:手勢驅動的互動、佈局過渡、基於滾動的效果以及共享元素過渡。

此技能針對 Reanimated 4(4.7.0,2026 年 9 月)。版本 4 僅適用於新架構,將 worklet 遷移到獨立的 react-native-worklets 套件,並新增了 CSS 風格的過渡和動畫。仍使用舊架構的應用程式應停留在 3.x 版本,該版本已不再積極維護。

使用時機

  • React Native 中任何超出簡單透明度/變換的動畫
  • 手勢驅動的互動(滑動刪除、拖曳重新排序、捏合縮放)
  • 滾動驅動的動畫(視差標題、黏性元素)
  • 佈局動畫(項目進入/離開列表)
  • 螢幕間的共享元素過渡(4.x 中為實驗性)

使用說明

設定

# Expo:安裝 SDK 鎖定的版本(SDK 57:Reanimated 4.5,Worklets 0.10,Gesture Handler 2.32)
npx expo install react-native-reanimated react-native-worklets react-native-gesture-handler
npx expo prebuild        # 僅開發建置:重新產生 ios/ 和 android/

# React Native Community CLI
npm install react-native-reanimated react-native-worklets react-native-gesture-handler
cd ios && pod install && cd ..
npm start -- --reset-cache
  • Expo: babel-preset-expo 會自動加入 Worklets Babel 外掛;請勿在 babel.config.js 中列出。
  • Community CLI: 在 babel.config.js 的 plugins 中加入 'react-native-worklets/plugin' 作為最後一個項目。Reanimated 3 的名稱 react-native-reanimated/plugin 在 4.x 中仍然可以解析,但這是舊的拼寫方式。
  • 每個 Reanimated 次要版本都接受特定的 react-native-worklets 和 React Native 版本(4.7 需要 Worklets 0.13 和 RN 0.86–0.88);在手動升級前請檢查相容性表格。
  • 對於手勢,請將應用程式根節點包裝在來自 react-native-gesture-handler 的 GestureHandlerRootView 中,並設定 style={{ flex: 1 }}。

Shared Value 與動畫樣式

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

export function FadeInCard({ children }: { children: ReactNode }) {
  const opacity = useSharedValue(0);
  const translateY = useSharedValue(20);
  useEffect(() => {
    opacity.value = withTiming(1, { duration: 600 });
    translateY.value = withSpring(0);
  }, []);
  const animatedStyle = useAnimatedStyle(() => ({
    opacity: opacity.value,
    transform: [{ translateY: translateY.value }],
  }));

  return <Animated.View style={[{ backgroundColor: "white", padding: 16 }, animatedStyle]}>{children}</Animated.View>;
}

僅在 effect、事件處理常式和 worklet 中讀寫 .value,切勿在渲染期間進行。使用 React Compiler 時,應使用 opacity.get() 和 opacity.set(1) 來代替 .value。

手勢動畫

// components/SwipeToDelete.tsx — 帶動畫的滑動手勢
import Animated, { useSharedValue, useAnimatedStyle, withSpring } from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { scheduleOnRN } from "react-native-worklets";
import type { ReactNode } from "react";

export function SwipeToDelete({ onDelete, children }: { onDelete: () => void; children: ReactNode }) {
  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);
        scheduleOnRN(onDelete);            // 從 UI 執行緒呼叫 JS 執行緒的函式
      } else {
        translateX.value = withSpring(0);  // 彈回
      }
    });
  const animatedStyle = useAnimatedStyle(() => ({ transform: [{ translateX: translateX.value }] }));
  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={animatedStyle}>{children}</Animated.View>
    </GestureDetector>
  );
}

scheduleOnRN(fn, ...args) 取代了在 4.x 中已棄用的 runOnJS(fn)(...args)。Gesture.Pan() 是 Gesture Handler 2 的建構器 API,也是 Expo SDK 57 安裝的版本;Gesture Handler 3 保留了它並新增了 hooks(usePanGesture({ onUpdate, onDeactivate }),其中 onStart/onEnd 被命名為 onActivate/onDeactivate)。

佈局動畫

// components/AnimatedList.tsx — 項目自動以動畫進入/離開
import Animated, { FadeInDown, FadeOutLeft, LinearTransition } from "react-native-reanimated";
import { Pressable, Text } from "react-native";

type Item = { id: string; title: string };
export function AnimatedList({ items, onRemove }: { items: Item[]; onRemove: (id: string) => void }) {
  return (
    <Animated.FlatList
      data={items}
      keyExtractor={(item) => item.id}
      itemLayoutAnimation={LinearTransition}   // 剩餘行滑入定位;僅限單列
      renderItem={({ item, index }) => (
        <Animated.View
          entering={FadeInDown.delay(index * 100).springify()}
          exiting={FadeOutLeft.duration(300)}
          style={{ backgroundColor: "white", padding: 16, marginVertical: 4, borderRadius: 8 }}
        >
          <Text>{item.title}</Text>
          <Pressable onPress={() => onRemove(item.id)}><Text style={{ color: "#dc2626" }}>移除</Text></Pressable>
        </Animated.View>
      )}
    />
  );
}

滾動驅動動畫

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

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], Extrapolation.CLAMP),
    opacity: interpolate(scrollY.value, [0, 200], [1, 0.3], Extrapolation.CLAMP),
  }));

  return (
    <>
      <Animated.View style={[{ backgroundColor: "#2563eb" }, headerStyle]}>
        <Text style={{ color: "white", fontSize: 28, fontWeight: "bold" }}>路徑日誌</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler}>{/* 內容 */}</Animated.ScrollView>
    </>
  );
}

當只需要偏移量時,useScrollOffset(animatedRef)(在 3.x 中命名為 useScrollViewOffset)會將其作為 shared value 返回,無需使用處理常式。

CSS 過渡與共享元素(Reanimated 4)

// 狀態變更會自動產生動畫:無需 shared value,無需 hook
<Animated.View
  style={{
    height: 80,
    width: expanded ? 240 : 120,
    backgroundColor: expanded ? "#16a34a" : "#2563eb",
    transitionProperty: ["width", "backgroundColor"],
    transitionDuration: 300,
  }}
/>

// 原生堆疊中兩個螢幕上的相同標籤會以動畫在它們之間轉換元素
<Animated.Image sharedTransitionTag="trail-42-photo" source={{ uri: photoUrl }} style={{ width: 120, height: 120 }} />

共享元素過渡在 4.x 中為實驗性功能,預設為關閉。在應用程式的 package.json(4.2+)中啟用它們,加入 "reanimated": { "staticFeatureFlags": { "ENABLE_SHARED_ELEMENT_TRANSITIONS": true } },然後重新建置原生應用程式;靜態標誌無法在 Expo Go 中變更。

範例

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

使用者提示:「建立一個 Tinder 風格的卡片滑動介面,並帶有流暢的動畫。」

// components/SwipeCard.tsx
import Animated, { interpolate, useAnimatedStyle, useSharedValue, withSpring, withTiming } from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { scheduleOnRN } from "react-native-worklets";
import { useWindowDimensions } from "react-native";
import type { ReactNode } from "react";

type Props = { children: ReactNode; onSwipe: (direction: "left" | "right") => void };
export function SwipeCard({ children, onSwipe }: Props) {
  const { width } = useWindowDimensions();
  const x = useSharedValue(0);
  const y = useSharedValue(0);
  const pan = Gesture.Pan()
    .onUpdate((e) => { x.value = e.translationX; y.value = e.translationY; })
    .onEnd((e) => {
      if (Math.abs(e.translationX) > width * 0.3) {
        const direction = e.translationX > 0 ? "right" : "left";
        x.value = withTiming(Math.sign(e.translationX) * width * 1.5, { duration: 200 }, (finished) => {
          if (finished) scheduleOnRN(onSwipe, direction);   // 在 React 狀態中移除卡片
        });
      } else {
        x.value = withSpring(0);
        y.value = withSpring(0);
      }
    });

  const style = useAnimatedStyle(() => ({
    transform: [{ translateX: x.value }, { translateY: y.value }, { rotate: `${interpolate(x.value, [-width, 0, width], [-15, 0, 15])}deg` }],
  }));

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

結果: 卡片跟隨手指並傾斜最多 15 度。在超過螢幕寬度 30% 處釋放時,它會飛出畫面,並在 JS 執行緒上執行 onSwipe("left" | "right");否則它會彈回中心位置。

範例 2:動畫底部選單

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

// components/BottomSheet.tsx
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from "react-native-reanimated";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { useWindowDimensions } from "react-native";
import type { ReactNode } from "react";

export function BottomSheet({ children }: { children: ReactNode }) {
  const { height } = useWindowDimensions();
  const snapPoints = [height * 0.1, height * 0.5, height * 0.85]; // 頂部邊緣:開啟、一半、預覽
  const top = useSharedValue(snapPoints[2]);
  const start = useSharedValue(0);
  const pan = Gesture.Pan()
    .onBegin(() => { start.value = top.value; })
    .onUpdate((e) => { top.value = Math.max(snapPoints[0], start.value + e.translationY); })
    .onEnd((e) => {
      const projected = top.value + e.velocityY * 0.2; // 拋擲後可能到達的位置
      const target = snapPoints.reduce((a, b) => (Math.abs(b - projected) < Math.abs(a - projected) ? b : a));
      top.value = withSpring(target, { velocity: e.velocityY });
    });

  const style = useAnimatedStyle(() => ({ transform: [{ translateY: top.value }] }));
  const sheet = { position: "absolute", left: 0, right: 0, top: 0, height, backgroundColor: "white" } as const;

  return (
    <GestureDetector gesture={pan}>
      <Animated.View style={[sheet, style]}>{children}</Animated.View>
    </GestureDetector>
  );
}

結果: 選單從預覽位置開始,跟隨拖曳動作,釋放時會彈跳到三個吸附點中最近的一個,並考慮到拋擲速度。

指南

  • 動畫狀態使用 Shared Value — useSharedValue 存在於 UI 執行緒;變更它不會重新渲染元件
  • 動態樣式使用 useAnimatedStyle — 在 UI 執行緒上重新計算
  • 自然運動使用 withSpring — 精確時長使用 withTiming。版本 4 更改了彈簧預設值(阻尼 120,剛度 900)並將 duration 視為感知上的持續時間;Reanimated3DefaultSpringConfig 可恢復舊的感覺
  • 從 Worklet 呼叫 JS 使用 scheduleOnRN — 傳遞在元件或模組作用域中定義的函式,而非在 worklet 內部建立的
  • Gesture Handler 整合 — Gesture.Pan()、Gesture.Pinch() 等;行內傳遞的回呼會自動 worklet 化,儲存在變數中的回呼需要加上 'worklet'; 指令
  • 佈局動畫是宣告式的 — Animated 元件上的 entering、exiting prop
  • 值映射使用 interpolate — 將滾動位置映射到透明度、縮放等;傳遞 Extrapolation.CLAMP 以在範圍邊界停止
  • Worklets Babel 外掛必須是最後一個 — 且在變更 Babel 配置後,清除 Metro 快取
  • 不要在 Worklet 中捕獲大型物件 — 捕獲的值會被複製到 UI 執行續;請傳遞 shared value、基本型別和小的純物件
  • 從 3.x 升級 — 首先啟用新架構,安裝 react-native-worklets,重新命名 Babel 外掛,並替換已被移除的 useAnimatedGestureHandler、useWorkletCallback 和 combineTransition
  • 何時不使用 — 一次性的淡入或滑動動畫(永遠不會阻塞)可以繼續使用 React Native 內建的 Animated API(原生的 CSS 過渡來自 Reanimated 本身);Reanimated 4 無法安裝在使用舊架構的應用程式中

Individual skills in this repo

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

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- You are an expert in AG2 (formerly AutoGen), the open-source multi-agent conversation framework. You help developers build systems where multiple AI agents collaborate through structured conversations — with tool use, human-in-the-loop, code execution, group chat orchestration, and nested conversations — for complex tasks like software development, research, and data analysis.

TerminalSkills/skills

>- Generate short-form videos with AI — script writing, text-to-speech narration, stock footage selection, subtitle generation, and video assembly. Use when: creating TikTok/YouTube Shorts/Reels content, automating video production, building content pipelines.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- Automate motion capture and tracking workflows in Blender with Python. Use when the user wants to import BVH or FBX mocap data, retarget motion to armatures, track camera or object motion from video, solve camera motion, clean up motion capture data, or script any tracking pipeline in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

相關技能