React Native中Gesture Handler的onGestureEvent不触发是怎么回事?
我在用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>
);
react-native-gesture-handler手势回调默认跑在UI线程,console.log是JS线程的方法,直接调用肯定没反应,甚至可能直接报错但没显示出来。简单说就是线程不通。你需要从
react-native-reanimated里引入runOnJS把你的打印操作包起来,这样它才能回到JS线程执行。复制这个改法:
另外记得检查
babel.config.js里有没有加react-native-reanimated/plugin插件,v2版本强依赖它。改完配置记得重新跑npm start并清一下缓存,不然装饰器语法都不认。