“冒泡"与“直接"React Native Android 自定义视图中的事件 [英] "bubbling" vs "direct" events in React Native Android custom view
问题描述
React Native Android 自定义视图能够在 ViewManager
子类中以两种不同的方式声明事件:
React Native Android custom views are able to declare events in 2 different ways in a ViewManager
subclass :
- 冒泡"事件通过
getExportedCustomBubblingEventTypeConstants()
- 通过
getExportedCustomDirectEventTypeConstants()
直接"事件
这两种类型的事件有什么区别?
What is the difference between these 2 types of event?
如果我尝试将事件从 Android 自定义视图 onClick(View v)
方法发送到我的视图的 JS 表示,我将使用这些方法中的哪一个来声明我的自定义事件名字?
If I am trying to send an event from an Android custom view onClick(View v)
method up to the JS representation of my view, which of these methods would I use to declare my custom event name?
跟进:我最终使用直接"事件从我的 Android 视图发送点击回到我的 JS 组件.这很有效,但我仍然想知道冒泡"事件是关于什么的.
Follow up: I ended up using a "direct" event to send a click from my Android view back to my JS component. This worked very well, but I would still like to know what the "bubbling" event is all about.
推荐答案
感谢您的回答 https://stackoverflow.com/a/44207488/2881112我能够掌握如何在 Android 中处理本机事件.
Thanks to your answer here https://stackoverflow.com/a/44207488/2881112 I was able to get a grasp on handling native events in Android.
经过大量实验后,我发现了这一点.
After experimenting a lot this is what I found out.
基本上有两种类型的事件
There are basically two types of events
- 直接事件 - 这似乎只影响自定义本机组件
- 冒泡事件 - 如果未由本机组件处理,则此事件会向上冒泡到父组件,直到处理为止.
示例:
如果我在自定义视图组件 CustomView
if I define getExportedCustomDirectEventTypeConstants
for onClick event on my custom view component CustomView
这样就行了
<CustomView onClick={() => console.log("Hello")}/>
但不是这个
<Pressable onPress={() => console.log("Hello")}>
<CustomView/>
</Pressable>
但是如果我使用
getExportedCustomBubblingEventTypeConstants
然后这两个都有效
<CustomView onClick={() => console.log("Hello")}/>
和
<Pressable onPress={() => console.log("Hello")}>
<CustomView/>
</Pressable>
这篇关于“冒泡"与“直接"React Native Android 自定义视图中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!