【问题标题】:Detect Swipe direction using React Native Gesture Handler and Reanimated使用 React Native Gesture Handler 和 Reanimated 检测滑动方向
【发布时间】:2020-03-15 06:58:26
【问题描述】:

我们已经使用 React Native PanResponder 开发了一个 swiper,(在有人评论之前) - 我们不能在这里使用任何其他 swiper 库。在我们开发的 swiper 中,我们面临一个问题,当用户结束 swipe(意味着释放 Pan)时,在启动 spring 动画时会有延迟。

因此,为了解决这个问题,我们正在尝试从 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
}

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

Gesture Handler 的问题来了,

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

我已经在 Gesture Handler 中搜索了问题,并找到了this

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

  1. 第一个是Sonaye,它有两个处理程序并检测到 在 onHandlerStateChange 中滑动两个处理程序的方向 这在使用 reanimated 时没有帮助,因为它只设置滑动方向 当处理程序状态发生变化时。
  2. 第二个是Satya,它实际上检测到滑动时 状态是 ACTIVE 但他使用 translationX 属性, translationX 属性也可以对我们不利并且可以移动 任一方向都类似于 swiper。

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

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

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

【问题讨论】:

    标签: react-native react-native-reanimated react-native-gesture-handler


    【解决方案1】:

    您可以通过属性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>
    );
    
    
    

    【讨论】:

      【解决方案2】:

      在我的例子中,我使用了 double FlingGestureHandler 来检测方向。它对我有用。

      【讨论】:

      • *双 FlingGestureHandlers
      • 请注意,您始终可以edit您的答案。所以没有必要使用 cmets 来更新你的答案。
      猜你喜欢
      • 1970-01-01
      • 2021-01-03
      • 2023-04-03
      • 2019-11-15
      • 1970-01-01
      • 2019-12-28
      • 2022-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多