[英]How can I pass a touch through a view in React Native but trigger the onPress?
I am trying to create a full screen touchable view that gets its onPress
triggered but also passes the touch down to the view behind it.我正在尝试创建一个全屏可触摸视图,该视图触发其
onPress
但也将触摸向下传递到其后面的视图。 In the example below, I'd like to have the onPress
function get called when the user scrolls on the scrollview.在下面的示例中,我希望当用户在滚动视图上滚动时调用
onPress
函数。 I'm able to get the scrollview to respond with pointerEvents="none"
on the Pressable
, but doing that makes the onPress
not get triggered.我能够让滚动视图在 Pressable 上使用
pointerEvents="none"
进行Pressable
,但是这样做会使onPress
不会被触发。 Is there any way to get both of these working together?有没有办法让这两者一起工作?
const styles = StyleSheet.create({
containingTouchable: {
position: 'absolute',
top: 0,
right: 0,
left: 0,
bottom: 0,
backgroundColor: 'rgba(100,100,100,0.3)',
},
});
const Component = () => {
<Pressable
style={styles.containingTouchable}
onPress={() => {
console.warn('pressed me');
}}
>
<View></View>
</Pressable>
<ScrollView> ... </ScrollView>
}
I would solve this using react-native-gesture-handler
.我会使用
react-native-gesture-handler
解决这个问题。 Instead of Pressable
, use TapGestureHandler
.取而代之的
Pressable
,使用TapGestureHandler
。 And import ScrollView
from react-native-gesture-handler
.并从
react-native-gesture-handler
导入ScrollView
。
Rngh provides a prop called simultaneousHandlers
so you can listen to multiple touch event at once. Rngh 提供了一个名为 concurrentHandlers 的道具
simultaneousHandlers
因此您可以一次收听多个触摸事件。
So you could do something like this:所以你可以做这样的事情:
const tapGestureHandlerRef = useRef(null);
<TapGestureHandler
ref={tapGestureHandlerRef}
onActivated={handleOnPress}
onHandlerStateChange={handleOnPress}
>
<ScrollView
simultaneousHandlers={tapGestureHandlerRef}
>
{content}
</ScrollView>
</TapGestureHandler
>
Both onActivated
and onHandlerStateChange
can trigger an onPress event, but they behave differently. onActivated
和onHandlerStateChange
都可以触发 onPress 事件,但它们的行为不同。 Take a look at the docs to see what fits your use case the best: https://docs.swmansion.com/react-native-gesture-handler/docs/api/gesture-handlers/tap-gh查看文档以了解什么最适合您的用例: https : //docs.swmansion.com/react-native-gesture-handler/docs/api/gesture-handlers/tap-gh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.