react-native 自带的 webview 替换为 react-native-webview 遇到的问题

mac2024-05-13  31

简单介绍下react-native-webview 替换  react-native 自带的 webview 的过程中 遇到的问题。

基于版本:

"react-native": "0.60.6", "react-native-webview": "^7.4.2",

1、安装及使用方法就省略了,可以看下react-native-webview这个文档。

2、react-native-webview 与 h5 交互。

 下面写出react-native-webview 的 webview 里的主要代码: 

import React, { Component } from 'react'; import { WebView } from 'react-native-webview'; /** * onMessage 接收HTML5 发送给 RN Webview 的消息 * */ onMessage = (event) => { let data = JSON.parse(event.nativeEvent.data); console.log("接收到的来自于html5的消息",data); } /** * RN Webview 发送消息给 HTML5 * data object * * 通过调用触发该函数 */ postMessageToH5(data){ this.webView.injectJavaScript(` (function(){ window.postMessage(${JSON.stringify(data)},'*'); })(); true; `) } class MyWeb extends Component { render() { return ( <WebView source={{ uri: 'https://infinite.red' }} style={{ marginTop: 20 }} ref={webView => this.webView = webView} onMessage={this.onMessage} /> ); } }

接下来写一下html5里的主要代码部分:

<script> /** * 发送消息给RN webview */ function onClick() { let postData = { type: 1, title: "测试" } // 发送消息 if(window.ReactNativeWebView){ window.ReactNativeWebView.postMessage(JSON.stringify(postData)) } } /** * 监听RN webview 发送到 html5 的消息 */ window.onload = function(){ window.addEventListener("message",function(msg){ let data = JSON.stringify(msg.data); console.log("接收RN发送过来的消息",data); }) } </script>

以上就是react-native-webview 与HTML5 的交互。跟 之前版本的 react-native 里的自带的Webview 与 html5  交互略有区别。 

 

3、react-native-webview 里的 originWhitelist 属性使用,把原本的

originWhitelist={['*']}

 替换写成

originWhitelist={["https://*", "http://*", "file://*", "sms://*", "tel://*"]}

这种方式可以解决一些链接报错问题。例如net :: ERR_UNKNOWN_URL_SCHEME 的问题。

最新回复(0)