How to handle the long PanResponder press event?

I am trying to handle long print in React Native via PanResponder. After a decent search, I could not find how to do this “correctly”, so I ask here. The idea is to execute the code when a long press (click) is detected on the screen. I went over 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 right for long presses or is there a better way?

+5
source share
2 answers

I ended this function with setTimeout . Here is the code that has functions for determining which part of the screen has been pressed for a long time (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'); } 
+7
source

I have a Carousel inside a ScrollView, and I wanted to know where the user clicked on the Carousel item. I did this thanks to @ 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 work perfectly on Android.

Note: it has not been tested on iOS

0
source

All Articles