[英]How to handle PanResponder long press event?
I am trying to handle a long press in React Native via PanResponder. 我试图通过PanResponder处理React Native中的长按。 After a decent search I couldn't find how to do it the "right way", so I am asking here. 经过一番体面的搜索,我无法找到“正确的方式”,所以我在这里问。 The idea is to execute code when a long press (click) on the screen is detected. 这个想法是在检测到屏幕上的长按(点击)时执行代码。 I have come up to something like this: 我有这样的事情:
handlePanResponderGrant(e, gestureState){
// On the press of the button set a timeout
myVar = setTimeout(this.MyExecutableFunction(), LONG_PRESS_MIN_DURATION);
}
handlePanResponderRelease(e, gestureState) {
// Clear the timeout if the press is released earlier than the set duration
clearTimeout(myVar);
}
Is this the right way to handle a long press or is there a better way? 这是处理长按的正确方法还是有更好的方法?
I ended up doing this functionality with setTimeout
. 我最终使用setTimeout
执行此功能。 Here is the code which has functionality to detect which part of the screen has been long pressed (left or right): 这是代码,它具有检测屏幕的哪个部分被长按(左或右)的功能:
handlePanResponderGrant(e, gestureState) {
console.log('Start of touch');
this.long_press_timeout = setTimeout(function(){
if (gestureState.x0 <= width/2 )
{
AlertIOS.alert(
'Left',
'Long click on the left side detected',
[
{text: 'Tru dat'}
]
);
}
else {
AlertIOS.alert(
'Right',
'So you clicked on the right side?',
[
{text: 'Indeed'}
]
);
}
},
LONG_PRESS_MIN_DURATION);
}
handlePanResponderMove(e, gestureState) {
clearTimeout(this.long_press_timeout);
}
handlePanResponderRelease(e, gestureState){
clearTimeout(this.long_press_timeout);
console.log('Touch released');
}
handlePanResponderEnd(e, gestureState) {
clearTimeout(this.long_press_timeout);
console.log('Finger pulled up from the image');
}
I have Carousel inside ScrollView, and I wanted to know where user pressed on the item of Carousel
. 我在ScrollView里面有Carousel ,我想知道用户在Carousel
的项目上按下了什么。 I ended up doing this thanks to @Alexander Netsov. 感谢@Alexander Netsov,我最终做到了这一点。
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onMoveShouldSetPanResponder: () => false,
onPanResponderGrant: (e, gestureState) => {
this.onLongPressTimeout = setTimeout(() => {
console.log("ON LONG PRESS", gestureState);
}, LONG_PRESS_DELAY);
},
onPanResponderRelease: () => {
clearTimeout(this.onLongPressTimeout);
},
onPanResponderTerminate: () => {
clearTimeout(this.onLongPressTimeout);
},
onShouldBlockNativeResponder: () => false,
onPanResponderTerminationRequest: () => true
});
Vertical ScrollView
, horizontal Carousel
and PanResponder
, all are working perfectly fine on Android. 垂直ScrollView
,水平Carousel
和PanResponder
,都在Android上完美运行。
Note: Its not tested on iOS 注意:它未在iOS上测试过
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.