简体   繁体   English

如何在 React-Native 中从内部 Touchable 到外部 Touchable 冒泡新闻事件?

[英]How to Bubbling press event from inner Touchable to outer Touchable in React-Native?

I've 2 nested Touchable s, I would like to capture the onPress event in either the outer Touchable and the inner Touchable , but only the inner one will fire the onPress event, so we can say that the event is not propagated to the parent element我有 2 个嵌套的Touchable ,我想在外部Touchable和内部Touchable捕获onPress事件,但只有内部一个会触发onPress事件,所以我们可以说该事件不会传播到父级元素

I'm using React-Native 0.57我正在使用 React-Native 0.57

This is my snack example .这是我的零食示例

I also repost my render code here:我也在这里重新发布我的渲染代码:

<TouchableOpacity onPress={() => alert('outer')}
    style={{ backgroundColor: 'red', width: 200, height: 200 }}>
    <TouchableOpacity onPress={() => alert('inner')}
        style={{ backgroundColor: 'green', width: 100, height: 100 }}
    />
</TouchableOpacity>

How you can see only the inner alert or the outer alert are showed.显示了如何只看到内部警报或外部警报。
Instead I would like to show either the outer and the inner alert pressing on the green View...相反,我想显示按下绿色视图的外部和内部警报...

The code is a simplified version, in the real case the inner Touchable is a component that can be used in various scenario, either inside a Touchable , either in non Touchable component代码是一个简化版本,在真实情况下,内部的Touchable是一个可以在各种场景中使用的组件,要么在Touchable内部,要么在非 Touchable 组件中

You could make the reusable component render conditionally either with View or TouchableOpacity depending on a property you pass it.您可以使用ViewTouchableOpacity使可重用组件有条件地呈现,具体取决于您传递给它的属性。

If you always want the outer component to trigger this will probably do the trick如果您总是希望外部组件触发,这可能会奏效

If you want to call the other TouchableOpacity 's onPress handler when one is triggered, just call it from the onPress handler of the one that is triggered.如果你想在触发时调用另一个TouchableOpacityonPress处理程序,只需从被触发的onPress处理程序调用它。

<TouchableOpacity onPress={myHandler}
    style={{ backgroundColor: 'red', width: 200, height: 200 }}>
    <TouchableOpacity onPress={myOtherHandler}
        style={{ backgroundColor: 'green', width: 100, height: 100 }}
    />
</TouchableOpacity>

If myOtherHandler is called by the inner-most TouchableOpacity 's onPress , you call myHandler like this:如果myOtherHandler由最内部称为TouchableOpacityonPress ,调用myHandler是这样的:

cost myOtherHandler = () => {
   myHandler(); 
   // ...other stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM