使用 React Native Gesture Handler 和 Reanimated 检测滑动方向

Ash*_*lal 4 react-native react-native-reanimated react-native-gesture-handler

我们已经使用 React Native PanResponder 开发了一个 swiper(在有人评论之前) - 我们不能在这里使用任何其他 swiper 库。在我们开发的滑动器中,当用户结束滑动(意味着释放平移)时,我们面临一个问题,启动弹簧动画时会出现滞后。

因此,为了解决这个问题,我们正在尝试从React Native Animated API迁移到Reanimated Libary,这可以解决用户面临的延迟问题。

但是,在使用React Native Gesture Handler (PanGestureHandler) 和 Reanimated Library 进行开发时,我们无法检测手势处理程序中的滑动方向。

我添加了用于检测 PanResponder 中滑动方向的代码部分

onPanMoving = (evt, {dx}) => {
   this.draggedEnd = dx < -this.swipeThreshold; //You are moving towards right screen
   this.draggedStart = dx > this.swipeThreshold; //You are moving towards left screen
}
Run Code Online (Sandbox Code Playgroud)

如您所见,在 PanResponder 中检测平移移动时的方向非常容易。

手势处理程序的问题来了,

当手势状态处于活动状态时,我无法检测到滑动

我已经在手势处理程序中搜索了问题,并发现了这个

该问题中建议了两种解决方法

  1. 第一个是由Sonaye开发的,它有两个处理程序,并在onHandlerStateChange中检测两个处理程序的滑动方向,这在使用 reanimated 时没有帮助,因为它仅在处理程序状态更改时设置滑动方向。
  2. 第二个是Satya提出的,它实际上在 State 处于 ACTIVE 时检测到滑动,但他使用TranslationX属性,translationX 属性对我们来说也可以为负,并且可以像 swiper 一样向任一方向移动。

这两种解决方法都不能解决我们的问题。

那么有没有其他方法可以使用 PanGestureHandler 和 Reanimated 来找到方向。我尝试将 PanResponder 与 Reanimated 和dx值一起使用,但最终收到错误消息,即仅支持 nativeEvent 属性,因为dx来自 PanResponder 的gestureState 参数。

注意:我们不能使用FlingGestureHandlerSwipeables,因为我们需要在 Fling 中仍然在 onHandlerStateChange 中找到方向,而 Swipeables 不使用 Reanimated。

小智 8

您可以通过属性水平滑动时检测方向velocityX

例子 :

const handleGesture = (evt) => {
    const { nativeEvent } = evt;

    if (nativeEvent.velocityX > 0) {
      console.log('Swipe right');
    } else {
      console.log('Swipe left');
    }
  };

return (
   <PanGestureHandler onGestureEvent={handleGesture}>
       // child component
   </PanGestureHandler>
);


Run Code Online (Sandbox Code Playgroud)