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、exitingprop - 值映射使用
interpolate— 將滾動位置映射到透明度、縮放等;傳遞Extrapolation.CLAMP以在範圍邊界停止 - Worklets Babel 外掛必須是最後一個 — 且在變更 Babel 配置後,清除 Metro 快取
- 不要在 Worklet 中捕獲大型物件 — 捕獲的值會被複製到 UI 執行續;請傳遞 shared value、基本型別和小的純物件
- 從 3.x 升級 — 首先啟用新架構,安裝
react-native-worklets,重新命名 Babel 外掛,並替換已被移除的useAnimatedGestureHandler、useWorkletCallback和combineTransition - 何時不使用 — 一次性的淡入或滑動動畫(永遠不會阻塞)可以繼續使用 React Native 內建的
AnimatedAPI(原生的 CSS 過渡來自 Reanimated 本身);Reanimated 4 無法安裝在使用舊架構的應用程式中