Communitygithub.com

React Native Reanimated

在原生UI线程上运行动画——无JS桥接瓶颈,无掉帧。即使在JavaScript线程繁忙时,动画也能保持60fps。它使用“worklet”——通过JSI在UI线程上执行的小型JavaScript函数。生产级 React Native 动画的标准:手势驱动交互、布局过渡、滚动效果和共享元素过渡。

React Native Reanimated 是什么?

该技能详细介绍了 React Native Reanimated 库,这是一个用于在原生UI线程上创建高性能动画的解决方案。它通过“worklet”机制绕过JS桥接,确保动画即使在主线程繁忙时也能保持60fps。技能涵盖了核心概念(共享值、动画样式、worklet)、基本设置(Babel插件、安装命令)以及多种实践场景,包括手势驱动动画(滑动删除)、布局动画(列表项的进出)、滚动驱动动画(视差头部)和共享元素过渡。用户可以通过具体的代码示例快速上手,并遵循最佳实践(例如将Babel插件放在最后、在worklet中仅使用共享值和基本类型)。该技能适用于开发 React Native 应用的开发者,能显著提升动画流畅度和交互体验。

兼容平台~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 桥接瓶颈,无掉帧。即使在 JavaScript 线程繁忙时,动画也能保持 60fps。它使用“worklet”——通过 JSI 在 UI 线程上执行的小型 JavaScript 函数。生产级 React Native 动画的标准:手势驱动交互、布局过渡、滚动效果和共享元素过渡。

何时使用

  • 任何超越简单透明度/变换的 React Native 动画
  • 手势驱动交互(滑动删除、拖拽排序、捏合缩放)
  • 滚动驱动动画(视差头部、粘性元素)
  • 布局动画(列表项进入/离开)
  • 屏幕间的共享元素过渡

说明

设置

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">我的应用</Text>
      </Animated.View>
      <Animated.ScrollView onScroll={scrollHandler} scrollEventThrottle={16}>
        {/* 内容 */}
      </Animated.ScrollView>
    </>
  );
}

示例

示例 1:构建卡片滑动界面

用户提示: “构建一个类似 Tinder 的卡片滑动界面,具有流畅动画。”

智能体将创建一个卡片栈,包含平移手势、基于滑动方向的旋转、用于回弹的弹簧动画,以及卡片移除时的布局过渡。

示例 2:带动画的底部抽屉

用户提示: “创建一个可以向上拖动并吸附到特定位置的底部抽屉。”

智能体将使用带吸附点的平移手势、用于高度的共享值,以及用于平滑吸附的弹簧动画。

指南

  • 使用共享值管理动画状态 — useSharedValue 在 UI 线程上运行
  • 使用 useAnimatedStyle 处理动态样式 — 在 UI 线程上重新计算
  • 使用 withSpring 实现自然运动 — withTiming 用于精确时长
  • 使用 runOnJS 从 worklet 调用 JS — 在需要时桥接回 JS 线程
  • 手势处理器集成 — Gesture.Pan(), Gesture.Pinch() 等
  • 布局动画是声明式的 — 在 Animated 组件上使用 entering、exiting 属性
  • 使用 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

相关技能