如何在 React Native 中检测整个屏幕上的向左滑动?
是否有必要使用 PanResponder 或者可以更容易地完成吗?
如何在 React Native 中检测整个屏幕上的向左滑动?
是否有必要使用 PanResponder 或者可以更容易地完成吗?
现有组件react-native-swipe-gestures
用于处理向上、向下、向左和向右方向的滑动手势,请参阅https://github.com/glepur/react-native-swipe-gestures
您可以使用react-native-swipe-gesture。你不需要使用 npm 安装任何第三方module。将文件下载到您的项目中并按照给定的步骤操作
我发现它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'}}
/>
我使用滚动视图和触摸位置制作了这个简单的解决方案。
它有一个非常干净的实现,没有沉重的组件或外部module。
您还可以将其用于组件而不是滚动视图。<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};
}
然后,在您的组件中……在我的情况下,我将使用: 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>
);
}
您可以使用该offsetRange
属性来处理精度。
并调整原始代码以用于普通类组件而不是钩子。
您可以使用React Native Gesture Handler,尽管它提供了比滑动更多的手势。这是一个滑动示例。