Gestures

作者 software-mansion-labse3f00cdb3494無授權條款291 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫10 天前更新

Software Mansion's best practices for gestures in React Native apps using React Native Gesture Handler. Use when implementing tap, pan, pinch, rotation, swipe, long press, fling, hover, drag, or any touch interaction. Trigger on: 'gesture handler', 'GestureDetector', 'tap gesture', 'pan gesture', 'pinch gesture', 'rotation gesture', 'long press', 'fling', 'hover gesture', 'swipe', 'pinch to zoom', 'drag', 'touch handling', 'Pressable', 'RectButton', 'Swipeable', 'Touchable', 'DrawerLayout', 'VirtualGestureDetector', or any request to handle user touch input in a React Native app.

AI 產生的概覽

在 React Native 應用程式中使用 React Native Gesture Handler 實作觸控手勢的最佳實務。

功能
提供在 React Native 中使用 React Native Gesture Handler 實作點擊、平移、捏合、旋轉、滑動、長按、快滑、懸停與拖曳互動的指引。內容涵蓋 v2 建構器 API 與 v3 Hook API 的版本差異、手勢組合、執行緒與 worklet 規則、捲動容器用法以及測試。產出的是實作建議與程式碼模式,而非檔案或指令碼。
適用情境
適用於在 React Native 應用程式中加入或偵錯觸控互動時,例如點擊、平移、捏合、滑動或拖曳處理。也適用於在多種手勢 API 之間做選擇、組合多個手勢,或從 v2 遷移到 v3 的情境。
執行需求
需要一個使用 react-native-gesture-handler 的 React Native 專案;部分內容涉及 Reanimated、react-native-worklets、Expo Router 或 React Navigation。不附指令碼;參考文件可能需要從網路取得。

React Native Gesture Handler

Software Mansion's production gesture patterns for React Native using Gesture Handler. Never suggest PanResponder when RNGH is available -- it runs on the JS thread and is effectively deprecated.

Version Decision Tree

Check package.json - "react-native-gesture-handler" version   │   ├── user asks to migrate v2 -> v3   │   → webfetch https://docs.swmansion.com/react-native-gesture-handler/docs/guides/upgrading-to-3   ├── starts with "2." → use builder API (Gesture.Pan(), Gesture.Simultaneous(), useMemo)   └── starts with "3." → use hook API (usePanGesture(), useSimultaneousGestures())

Key API Differences (v2 vs v3)

Conceptv2 Builder APIv3 Hook API
Create gestureGesture.Pan().onUpdate(...)usePanGesture({ onUpdate: ... })
Compose (simultaneous)Gesture.Simultaneous(a, b)useSimultaneousGestures(a, b)
Compose (race/competing)Gesture.Race(a, b)useCompetingGestures(a, b)
Compose (exclusive)Gesture.Exclusive(a, b)useExclusiveGestures(a, b)
Activation callback.onStart(...)onActivate: ...
Deactivation callback.onEnd(...)onDeactivate: ...
Change data.onChange(...)merged into onUpdate (use changeX, changeY)
Cross-component.simultaneousWithExternalGesture().simultaneousWith()
Cross-component.requireExternalGestureToFail().requireToFail()
Cross-component.blocksExternalGesture().block()
Memoizationwrap in useMemo (mandatory)hook input needs memoization (supports React Compiler)
SVG / broken hierarchyGestureDetector (may break hierarchy)InterceptingGestureDetector + VirtualGestureDetector
State managercallback param stateManagerglobal GestureStateManager
ButtonsRectButton, BorderlessButtonTouchable

Critical Rules

GestureHandlerRootView is mandatory -- GestureDetector will crash at runtime without it as an ancestor. Place it as close to the app root as possible. With Expo Router, wrap <Stack /> in the root _layout.tsx:

tsx
// app/_layout.tsximport { Stack } from 'expo-router';import { GestureHandlerRootView } from 'react-native-gesture-handler';
export default function RootLayout() {  return (    <GestureHandlerRootView>      <Stack />    </GestureHandlerRootView>  );}

With React Navigation (no Expo Router), wrap the <NavigationContainer> children. With bare React Native, wrap the app root component. Nested GestureHandlerRootViews are ignored -- only the topmost instance is used. Default style is { flex: 1 }.

v2: useMemo every gesture -- without it, gesture objects recreate on every render, causing recognizers to re-attach and lose state:

tsx
const pan = useMemo(() => Gesture.Pan().onBegin(...).onUpdate(...).onEnd(...), []);

v3 hook API handles memoization internally, but the input object must be memoized for it to work correctly.

Never call JS-thread functions directly from gesture callbacks -- when Reanimated is installed, gesture callbacks run on the UI thread (workletized). Calling any non-worklet function (state setters, navigation, audio APIs, native module methods, useCallback handlers) directly from a gesture callback crashes with "Tried to synchronously call a non-worklet function on the UI thread". Wrap every JS-thread call in scheduleOnRN from react-native-worklets:

tsx
import { scheduleOnRN } from 'react-native-worklets';
// WRONG -- crashes: calling JS function directly from UI threadconst gesture = useMemo(() =>  Gesture.Pan().onUpdate((e) => {    handleTouch(e.absoluteX, e.absoluteY); // non-worklet function  }),[]);
// CORRECT -- schedules JS function on RN threadconst gesture = useMemo(() =>  Gesture.Pan().onUpdate((e) => {    scheduleOnRN(handleTouch, e.absoluteX, e.absoluteY);  }),[]);

This applies to all gesture callback types including onTouchesDown, onTouchesMove, onTouchesUp, onStart, onUpdate, onEnd, etc. The only code safe to run directly is worklet-compatible code (shared value mutations, other worklet functions).

Scroll containers -- import ScrollView/FlatList from react-native-gesture-handler, not react-native. Use RectButton (v2) or Touchable (v3) for tappable items inside scroll containers:

tsx
import { ScrollView, FlatList, RectButton, Touchable } from 'react-native-gesture-handler';

Never mix React Native touch handlers with RNGH in the same component tree -- causes double-tap bugs and gesture conflicts. Pick one system per app.

Callbacks are auto-workletized -- do not add 'worklet'; to callbacks passed directly (inline) to gesture hooks/builders. The Babel plugin handles this. Only add 'worklet'; to standalone functions assigned to variables before being passed as callbacks.

References

Load at most one reference file per question. For API signatures and config options, webfetch the documentation pages linked in each reference file.

FileWhen to read
gestures.mdChoosing which gesture type or component to use; callback lifecycle; threading model; GestureStateManager for manual activation; SharedValue in gesture config
tap-handling.mdRectButton, Pressable, Touchable, tappable items in scroll containers, tap gestures, double-tap, hit slop
continuous-gestures.mdPan (drag), Pinch (zoom), Rotation, Long press, Fling (swipe), Hover; Reanimated integration patterns; offset accumulation; velocity and decay
gesture-composition.mdCombining gestures on one component (Simultaneous/Race/Exclusive); cross-component relations; VirtualGestureDetector for SVG and Text; Pan inside ScrollView
swipeable-and-drawer.mdReanimatedSwipeable for list item actions; ReanimatedDrawerLayout for side menus; custom swipeable with Pan gesture; web scroll compatibility
testing.mdJest setup and mocking; fireGestureHandler for testing gestures; common troubleshooting (multiple instances, gesture conflicts, enabled timing)
v2-to-v3-migration.mdMigration guide from v2 to v3; API changes; hook usage; memoization; gesture callbacks

來源與署名

來源:software-mansion-labs/skills位於skills/react-native-best-practices/references/gestures提交e3f00cd

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架