Communitygithub.com

React Native Reanimated

一个用于 React Native 的动画库,通过 worklets 和共享值在 UI 线程上运行动画,确保在 JavaScript 线程繁忙时动画依然流畅。适用于“在 React Native 中实现动画”、“Reanimated”、“流畅的移动端动画”、手势动画、共享元素过渡以及升级到 Reanimated 4 等场景。

React Native Reanimated 是什么?

React Native Reanimated 是一个专业的动画库,它通过将动画执行从 JavaScript 线程转移到原生 UI 线程,实现了 60fps(或设备刷新率)的流畅动画。核心机制是“worklets”——一种能在 UI 线程上通过 JSI 执行的小型 JavaScript 函数。该技能专注于 Reanimated 4 版本(4.7.0),它仅在新架构下工作,将 worklets 分离到独立的 `react-native-worklets` 包中,并新增了 CSS 风格的过渡和动画。技能涵盖了从基础设置(Expo 和社区 CLI)、共享值与动画样式、手势驱动动画(如滑动删除、卡片滑动)、布局动画(列表的进出过渡)、滚动驱动动画(视差效果)到高级特性(CSS 过渡和共享元素过渡)。它提供了完整的代码示例,如构建 Tinder 式卡片滑动界面和可拖拽的快照式底部弹窗,并给出了清晰的最佳实践指南,包括何时使用 `withSpring` 与 `withTiming`、如何从 3.x 迁移,以及何时应该继续使用 React Native 内置的 `Animated` API。

兼容平台~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(或设备刷新率)。它使用“worklets”:通过 JSI 在 UI 线程上执行的小型 JavaScript 函数。它是 React Native 中生产级动画的标准:手势驱动交互、布局过渡、基于滚动的效果和共享元素过渡。

本技能针对 Reanimated 4(4.7.0,2026 年 9 月)。版本 4 仅在新架构下工作,将 worklets 移至单独的 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: 将 'react-native-worklets/plugin' 添加为 babel.config.js 中 plugins 的 最后 一项。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 }}。

共享值和动画样式

// components/FadeIn.tsx — 使用共享值的基本动画
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" }}>Remove</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" }}>Trail Log</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler}>{/* Content */}</Animated.ScrollView>
    </>
  );
}

当只需要偏移量时,useScrollOffset(animatedRef)(在 3.x 中名为 useScrollViewOffset)可以直接返回一个共享值,无需处理器。

CSS 过渡和共享元素(Reanimated 4)

// 状态变化自动动画:无需共享值,无需 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>
  );
}

**结果:**弹窗从预览位置开始,跟随拖拽,释放时根据手指抬起速度,弹性吸附到三个吸附点中最近的一个。

指南

  • 用于动画状态的共享值 — useSharedValue 存在于 UI 线程上;更改它不会重新渲染组件
  • useAnimatedStyle 用于动态样式 — 在 UI 线程上重新计算
  • withSpring 用于自然的运动 — withTiming 用于精确的持续时间。版本 4 更改了弹簧默认值(阻尼 120,刚度 900),并将 duration 视为感知持续时间;Reanimated3DefaultSpringConfig 可恢复旧手感
  • scheduleOnRN 用于从 worklet 调用 JS — 传递在组件或模块作用域中定义的函数,而不是在 worklet 内部创建的
  • Gesture Handler 集成 — Gesture.Pan()、Gesture.Pinch() 等;内联传递的回调会自动 worklet 化,存储在变量中的回调需要 'worklet'; 指令
  • 布局动画是声明式的 — Animated 组件上的 entering、exiting props
  • interpolate 用于值映射 — 将滚动位置映射到透明度、缩放等;传递 Extrapolation.CLAMP 以在范围边界停止
  • Worklets Babel 插件必须是最后一个 — 更改 Babel 配置后,清除 Metro 缓存
  • 不要在 worklet 中捕获大型对象 — 捕获的值会被复制到 UI 运行时;传递共享值、原始值和小型纯对象
  • 从 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.

相关技能