2016-08-03 44 views
5

我想通過PanResponder處理React Native中的長按操作。經過一次體面的搜索後,我無法找到如何做到「正確的方式」,所以我在這裏問。這個想法是在檢測到屏幕上長按(點擊)時執行代碼。 我已經長到了這樣的事情:如何處理PanResponder長按事件?

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); 
} 

這是處理長按正確的方式還是有更好的辦法?

+0

'this.MyExecutableFunction()未測試'必須是'this.MyExecutableFunction'和'clearTimeout(myVar的)'具有在'handlePanResponderTerminate'以及執行,確保在按下終止後,應用程序不會將其計爲長按。 –

回答

7

我最終用setTimeout來做這個功能。這裏是一個具有以下功能:檢測屏幕的哪個部分已長按(左或右)代碼:

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'); 
} 
+0

確保設置'onShouldBlockNativeResponder'在Android設備的'PanResponder'上返回'false',否則,'PanResponder'將劫持該手勢並且不允許正常滾動。 –

0

Carousel內滾動型的,我想知道用戶按下上的Carousel項目。 @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 
}); 

垂直ScrollView,水平CarouselPanResponder,所有的工作都在Android上完美的罰款。

注意:它在iOS