react-native-gesture-handler的GestureDetector调用外部函数致APP崩溃
问题原因与解决方案
这不是GestureDetector的bug,是因为手势回调函数运行在工作线程,而普通的React函数(比如trigger)属于JS线程上下文,直接跨线程调用会导致上下文冲突引发崩溃。
解决方法
使用react-native-reanimated提供的runOnJS函数,将需要调用的外部函数包裹后,再在手势回调中执行:
- 先导入
runOnJS:
import Animated, { useAnimatedStyle, useSharedValue, withTiming, runOnJS } from 'react-native-reanimated';
- 修改手势回调中的函数调用:
const flingGesture = Gesture.Fling() .direction(Directions.RIGHT) .onStart((e) => { position.value = withTiming(position.value + 10, { duration: 100 }); console.log(e); runOnJS(trigger)(); // 用runOnJS包裹trigger并执行 }); const flingGestureLeft = Gesture.Fling() .direction(Directions.LEFT) .onStart((e) => { position.value = withTiming(position.value - 10, { duration: 100 }); runOnJS(trigger)(); });
原理说明
react-native-gesture-handler的手势回调默认在非JS线程的工作线程执行,目的是避免手势处理阻塞UI。但React的状态更新、普通JS函数调用必须在JS线程中进行,runOnJS的作用就是将函数调度到JS线程执行,确保上下文正确。
内容的提问来源于stack exchange,提问作者Michel Gisenaël
相关产品推荐
相关产品推荐

