【问题标题】:TouchableOpacity swallow touch event and never passTouchableOpacity 吞下触摸事件并且永不通过
【发布时间】:2017-03-27 03:09:13
【问题描述】:

我试图让onPress 都发生在TouchableOpacity,但第二个是唯一触发的:

<TouchableOpacity onPress={() => console.warn('first button')}>
  <TouchableOpacity onPress={() => console.warn('second button')}>
    <Text>
      PRESS ME
    </Text>
  </TouchableOpacity>
</TouchableOpacity>

我怎样才能让它们都着火?

提前致谢!

【问题讨论】:

  • 我认为你不能这样做——这不是 React Native 中的触摸响应系统的工作方式。也许您可以描述一下您为什么要这样做以及您要达到的目标,并且可能有更好的解决方案?
  • 如果您的用例如此简单,为什么不将您的 2 个 TouchableOpacity 合并为一个?

标签: react-native touchableopacity


【解决方案1】:

您可以简单地使用“ref”概念并调用道具 onPress 来触发它们。

<TouchableOpacity onPress={() => 
  AlertIOS.alert('firstbutton')
  } 
  ref={component => this.myFirstTouchable = component}
>
    <TouchableOpacity onPress={() => 
        {
        AlertIOS.alert('second')
        this.myFirstTouchable.props.onPress()
        }
    }>
        <Text>
          PRESS ME
        </Text>
      </TouchableOpacity>
    </TouchableOpacity>

【讨论】:

  • 谢谢,但我不喜欢使用ref,它不是最佳实践之一,只有在没有其他解决方案的情况下才应该使用它
  • 您实际上要求在应用程序中避免某些事情(2 个可触摸元素在同一个地方执行 2 个不同的操作)。
  • ref 不是“坏习惯”!通过 this.refs.myString 访问 ref 不是通过 ref 回调访问元素。有许多使用 ref 回调的库。甚至 RN 本身...(查看 UIExplorer 示例)来自 React 文档:使用 ref 回调来设置类的属性是访问 DOM 元素的常见模式。如果您当前正在使用 this.refs.myRefName 来访问 refs,我们建议您改用此模式。
猜你喜欢
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多