2016-08-03 99 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