2019-04-03
使用WebView组件可以显示一个HTML网页,这里记录一下react-native如何跟HTML页面进行通信,即实现双向的事件调用和数据传递。
一、React-Native调用HTML页面事件
1、在HTML页面添加对RN事件的监听,。
window.onload = function(){
addReactNativeListener();
};
/**
* document.addEventListener("message",function(event) {}
* 监听RN发送的事件,通过event.data获取传递过来的参数值
*/
function addReactNativeListener() {
document.addEventListener("message",function(event) {
document.getElementById("showInfoElement").innerHTML = "RN发送事件到HTML页面,传递过来的参数:" + event.data;
});
}
2、RN端发送事件,我们通过一个按钮事件来执行这个操作。
<Button title={'RN发送事件到HTML页面'} onPress={() => {
this.refs.webView.postMessage("RN发送事件到HTML页面");
}}/>
postMessage()只能传递一个字符串参数,通常会使用JSON字符串,携带操作标识和相关参数,以完成多种业务操作。这里是简单的传递了一个字符串。
3、IOS端效果
二、HTML页面调用React-Native事件
1、编写一段HTML代码,WebView加载显示本地的HTML。
const HTML = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>WebView组件与HTML页面通信机制实践</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<button onclick="sendEventToReactNative()" >发送事件到React-Native端</button>
</div>
<p>React-Native WebView组件与HTML页面通信机制实践</p>
<div id="showInfoElement"></div>
</body>
<script>
window.onload = function(){
addReactNativeListener();
};
/**
* document.addEventListener("message",function(event) {}
* 监听RN发送的事件,通过event.data获取传递过来的参数值
*/
function addReactNativeListener() {
document.addEventListener("message",function(event) {
document.getElementById("showInfoElement").innerHTML = "RN发送事件到HTML页面,传递