react-native-webview与前端的交互

使用方法

使用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}
          />
              
js发消息给RN
//Flutter 接收  
   /**
     * onMessage 接收HTML5 发送给 RN Webview 的消息
     *
     */
    onMessage = (event) => {
        // let data = JSON.parse(event.nativeEvent.data);
        console.log('接收到的来自于html5的消息', event.nativeEvent.data);
    };

RN发消息给js
this.webView.postMessage('RN向H5发送的消息');

注意上面一定要声明出来 ref={webView => this.webView = webView}

HTML代码
<!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>

猜你喜欢

转载自blog.csdn.net/TLuffy/article/details/106694194