javascript - React Native:如何暂时禁用 PanResponder?
下面是创建 panResponder 实例的代码片段:
constructor( props ) {
super( props );
this.position = new Animated.ValueXY();
this.panResponder = PanResponder.create( {
onStartShouldSetPanResponder: ( ) => true,
onPanResponderMove: ( event, gesture ) => {
this.position.setValue( { x: 0, y: gesture.dy } );
},
onPanResponderRelease: ( event, gesture ) => {
if ( gesture.dy > SWIPE_THRESHOLD ) {
this.forceSwipe( 'up' );
} else if ( gesture.dy < -SWIPE_THRESHOLD ) {
this.forceSwipe( 'down' );
} else {
this.resetPosition();
}
},
onMoveShouldSetPanResponderCapture: ( evt, gestureState ) =>
gestureState.dx !== 0 && gestureState.dy !== 0,
} );
}
getCardStyle() {
return {
...this.position.getLayout(),
};
}
下面是我的组件的代码片段:
<Animated.View
key={ item.id }
style={ [ this.getCardStyle(), styles.cardStyle ] }
{ ...this.panResponder.panHandlers }
>
<Card
shouldPanRespond={ this.shouldPanRespond }
item={ item }
/>
</Animated.View>
卡片组件的代码片段:
<TouchableOpacity
activeOpacity={ 1 }
style={ cardStyle }
onPress={ this.onPress }
>
<ScrollView contentContainerStyle={ cardStyle }>
<Image
resizeMode="cover"
style={ imageStyle }
source={ { uri: img_url } }
/>
<View style={ titleWrapStyle }>
<Text style={ textStyle }>{ title }</Text>
</View>
</ScrollView>
</TouchableOpacity>
我正在构建绝对定位的卡片,一张叠在另一张的后面。这些卡片可以使用panResponder向上或向下滑动。但是,当点击屏幕时,我应该在同一屏幕上显示详细页面。
现在,我可以检测到点击,但每当用户点击/轻触时,我想禁用panResponder,以便卡片不能被滑动,用户可以滚动浏览内容。一旦用户滚动到底部,我想重新启用滑动,也就是说我想启用平移。
我知道 onStartShouldSetResponder:() => false 会禁用 panResponder,但我们如何在创建实例后禁用它。我在其他地方没找到太多相关信息。
答案#1
对于那些想要了解如何暂时禁用 PanResponder 的人,以下是我的解决方案。
正如 @RaHuL - House Javascript 注意到的,另一个答案并没有真正解决问题,因为将 onStartShouldSetResponder 设置为对应某个状态值(可能会从 true 变为 false)的值,如果 PanResponder 是用 true 创建的,那么不会影响 PanResponder(至少看起来是这样)。
我通过修改 onPanResponderMove 函数解决了类似的问题。我在状态中有一个值:panResponderEnabled,我的函数如下所示:
onPanResponderMove: ( event, gesture ) => {
if(this.state.panResponderEnabled){
this.position.setValue( { x: 0, y: gesture.dy } );
}
}
当我不想读取来自 PanResponder 的更改时,我只需将 panResponderEnabled 设置为 false。
答案#2
如果你想要一个非常简单的暴力解决方案,可以在动画视图上使用 pointerEvents 属性。
pointerEvents={stopPan ? 'none' : 'auto'}当 stopPan 为 true 时,这将阻止视图及其下方的所有触摸事件触发。
