React Native中如何禁用TouchableOpacity子View的触摸响应?
解决React Native中子View点击触发父组件触摸事件的问题
问题原因
你给黄色View设置pointerEvents="none"后,触摸事件会直接穿透到父级的TouchableOpacity,所以仍然会触发onPress。这个属性仅让View自身不响应触摸,但不会阻止事件向上传递给父组件。
解决方案
方案一:阻止事件冒泡
给黄色View设置pointerEvents="box-only"(让它能接收触摸事件),再通过onTouchStart事件阻止事件向上冒泡:
import { Text, TouchableOpacity, View } from "react-native" import React from "react" export default function Screen() { const stopPropagation = (event) => { event.stopPropagation(); } return ( <TouchableOpacity style={{ flex: 1, backgroundColor: "black" }} onPress={() => console.log("pressed")} > <View style={{ width: 100, height: 100, backgroundColor: "yellow" }} pointerEvents="box-only" onTouchStart={stopPropagation} > <Text>React Native</Text> </View> </TouchableOpacity> ) }
方案二:用禁用的TouchableOpacity包裹子View
将黄色View放在一个禁用的TouchableOpacity中,它会拦截触摸事件,不会传递给父组件:
import { Text, TouchableOpacity, View } from "react-native" import React from "react" export default function Screen() { return ( <TouchableOpacity style={{ flex: 1, backgroundColor: "black" }} onPress={() => console.log("pressed")} > <TouchableOpacity style={{ width: 100, height: 100, backgroundColor: "yellow" }} disabled={true} activeOpacity={1} > <Text>React Native</Text> </TouchableOpacity> </TouchableOpacity> ) }
原理说明
- 方案一中,
pointerEvents="box-only"让View可以捕获触摸事件,stopPropagation()则切断了事件向上传递的路径,父组件无法收到该触摸事件。 - 方案二中,禁用的
TouchableOpacity会消费触摸事件,既不触发自身的点击逻辑,也不会将事件传递给父级组件。
内容的提问来源于stack exchange,提问作者Nemesis
相关产品推荐
相关产品推荐

