React Native WebView 内点击事件获取
问题描述:
- 在RN的WebView里边,很多时候需要获取一个点击事件,来操作原生代码处理一些事情。可以使用onNavigationStateChange、onMessage来解决
代码
通过onNavigationStateChange :官方文档是这么写的Function that is invoked when the WebView loading starts or ends.那么这个方法到底是做什么的呢?
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
其中不难发现,我们刚进入webview的时候 navigationType 为other,而点击跳转的时候则为click,好吧说到这里,估计大家都应该明白这个方法是做什么了。注意:这个方法无法阻止页面的跳转行为,所以大家只能通过这个方法获取用户的一些行为。从而做出判断。
但有很多情况,我们都是想,获取到这个行为,传值到RN再做其他事情,下面就做一个简单的例子onMessage。官方文档是这样描述的:
A function that is invoked when the webview calls window.postMessage. Setting this property will inject a postMessage global into your webview, but will still call pre-existing values of postMessage.
window.postMessage accepts one argument, data, which will be available on the event object, event.nativeEvent.data. data must be a string.
可以看出,这个方法用来和RN进行交互,必须注意的就是 当webview显示的页面中有 postMessage的同名函数时将会报错。
onMessage(func)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
估计大家看到这里 应该脑洞大开了,这样在RN中就能够获取 标签、用户行为、交互数据。转载http://blog.youkuaiyun.com/u011690583/article/details/68922118