使用npm或者yarn安装react-native-webview。
<WebView
//html文件放在Android --> app --> src --> main --> assets文件夹下,html代码下面会给出来可以参考
source={{uri: 'file:///android_asset/index.html'}}
style={{marginTop: 0}}
ref={webView => this.webView = webView}
onMessage={this.onMessage}
useWebKit={true}
javaScriptEnabled={true}
/>
//Flutter 接收
/**
* onMessage 接收HTML5 发送给 RN Webview 的消息
*
*/
onMessage = (event) => {
// let data = JSON.parse(event.nativeEvent.data);
console.log('接收到的来自于html5的消息', event.nativeEvent.data);
};
this.webView.postMessage('RN向H5发送的消息');
注意上面一定要声明出来 ref={webView => this.webView = webView}
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="renderer" content="webkit">
<meta http-equiv="Cache-Control" content="no-siteapp">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./build/calendar.css">
<style>
.btn{
background: #f00;color:#fff
}
</style>
</head>
<body style="background:#ddd;">
<div style="text-align: center">
<button id="button" onclick="send()">发送数据到react native</button>
<p style="text-align: center">收到react native发送的数据: <span id="data"></span></p>
</div>
</body>
<script>
var data = 0;
function send () {
data += 100;
window.ReactNativeWebView.postMessage("Hello React");
}
window.onload = function () {
document.addEventListener('message', function (e) {
document.getElementById('data').textContent = e.data;
});
}
</script>
</html>