React Native中Gesture Handler的onGestureEvent不触发是怎么回事?

UI春光 阅读 5

我在用react-native-gesture-handler做自定义拖动手势,但onGestureEvent完全没反应,控制台也不打印。试过把View换成Animated.View,也加了import 'react-native-gesture-handler',还是不行。

我的代码大概是这样:

const gesture = Gesture.Pan().onStart(() => {
  console.log('start');
}).onUpdate((e) => {
  console.log('update', e.translationX);
});

return (
  <GestureHandlerRootView style={{ flex: 1 }}>
    <GestureDetector gesture={gesture}>
      <Animated.View style={{ width: 100, height: 100, backgroundColor: 'red' }} />
    </GestureDetector>
  </GestureHandlerRootView>
);
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
司空晓曼
你这是典型的v2版本用法没搞对。新版的react-native-gesture-handler手势回调默认跑在UI线程,console.log是JS线程的方法,直接调用肯定没反应,甚至可能直接报错但没显示出来。

简单说就是线程不通。你需要从react-native-reanimated里引入runOnJS把你的打印操作包起来,这样它才能回到JS线程执行。

复制这个改法:

import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, { runOnJS } from 'react-native-reanimated';

// 单独把JS线程的逻辑抽出来
const handleLog = (msg) => {
console.log(msg);
};

const gesture = Gesture.Pan()
.onStart(() => {
'worklet';
// 必须用runOnJS包一层
runOnJS(handleLog)('start');
})
.onUpdate((e) => {
'worklet';
// console.log也不能直接用
runOnJS(console.log)('update', e.translationX);
});


另外记得检查babel.config.js里有没有加react-native-reanimated/plugin插件,v2版本强依赖它。改完配置记得重新跑npm start并清一下缓存,不然装饰器语法都不认。
点赞
2026-03-01 20:07