You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 09:10:28