检测React Native中的左侧滑动

Jam*_*een 12 javascript node.js reactjs react-native

如何在React Native中检测整个屏幕上的左侧滑动?

是否有必要使用PanResponder或者它可以更轻松一点吗?

Kuz*_*ave 41

我使用滚动视图和触摸位置制作了这个简单的解决方案。 它有一个非常干净的实现,没有重型组件或外部模块。 您还可以将其与组件一起使用而不是滚动视图。

<View>

首先,我们将创建一个钩子useSwipe.tsx

import { Dimensions } from 'react-native';
const windowWidth = Dimensions.get('window').width;

export function useSwipe(onSwipeLeft?: any, onSwipeRight?: any, rangeOffset = 4) {

    let firstTouch = 0
    
    // set user touch start position
    function onTouchStart(e: any) {
        firstTouch = e.nativeEvent.pageX
    }

    // when touch ends check for swipe directions
    function onTouchEnd(e: any){

        // get touch position and screen size
        const positionX = e.nativeEvent.pageX
        const range = windowWidth / rangeOffset

        // check if position is growing positively and has reached specified range
        if(positionX - firstTouch > range){
            onSwipeRight && onSwipeRight()
        }
        // check if position is growing negatively and has reached specified range
        else if(firstTouch - positionX > range){
            onSwipeLeft && onSwipeLeft()
        }
    }

    return {onTouchStart, onTouchEnd};
}
Run Code Online (Sandbox Code Playgroud)

然后,在你的组件中......就我而言,我将使用:exampleComponent.tsx

  • 导入之前的useSwipe钩子。
  • onTouchStart将和onTouchEnd事件添加到您的滚动视图中。

示例组件

import * as React from 'react';
import { ScrollView } from 'react-native';
import { useSwipe } from '../hooks/useSwipe'

export function ExampleComponent(props: any) {
    const { onTouchStart, onTouchEnd } = useSwipe(onSwipeLeft, onSwipeRight, 6)

    function onSwipeLeft(){
        console.log('SWIPE_LEFT')
    }

    function onSwipeRight(){
        console.log('SWIPE_RIGHT')
    }
   
    return (
        <ScrollView onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
            {props.children}
        </ScrollView>
    );
}
Run Code Online (Sandbox Code Playgroud)

您可以随意调整该offsetRange属性来处理精度。
并调整原始代码以与普通类组件一起使用,而不是与钩子一起使用。


Dan*_*hka 39

我发现它react-native-swipe-gestures不稳定(在 Android 上滑动是随机的)并且react-native-gesture-handler过于复杂(仅仅添加到项目中需要付出太多的努力)。

基于 Kuza Grave 的答案的简化解决方案,他的解决方案完美且非常简单:

<View
      onTouchStart={e=> this.touchY = e.nativeEvent.pageY}
      onTouchEnd={e => {
        if (this.touchY - e.nativeEvent.pageY > 20)
          console.log('Swiped up')
      }}
      style={{height: 300, backgroundColor: '#ccc'}}
    />
Run Code Online (Sandbox Code Playgroud)


Bha*_*tel 15

有一个现有组件'react-native-swipe-gestures',

React Native组件,用于处理向上,向下,向左和向右方向的滑动手势.

消息来源:https://github.com/glepur/react-native-swipe-gestures

  • 这仍然相关吗?github页面两年没更新了 (2认同)

Tar*_*kur 5

您可以使用React Native Gesture Handler,尽管它提供了比滑动更多的手势。这是一个滑动示例


Nik*_*eni 5

您可以使用react-native-swipe-gesture。您不需要使用npm安装任何第三方模块。将文件下载到您的项目中,然后按照给定的步骤进行操作

  • 值得一提的是,Nikhil Gogineni 似乎是 https://github.com/nikhil-gogineni/react-native-swipe-gesture/ 的作者,由于源代码如此简短且易于审查,恕我直言没有错关于那个。 (2认同)
  • 谢谢!希望这个模块有帮助!@B--rian (2认同)