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
您可以使用react-native-swipe-gesture。您不需要使用npm安装任何第三方模块。将文件下载到您的项目中,然后按照给定的步骤进行操作
归档时间: |
|
查看次数: |
19245 次 |
最近记录: |