React Native 從零單排8 html通信

RN版本:0.64
系統:Win10

前言

開發RN應用的的時候,遇到過一個問題,由于業務比較復雜,頁面數據比較龐大,在操作工程中會遇到頁面re-render過度的情況,但是優化起來也很難,于是想到用WebView內嵌html的方式來處理這個頁面避免re-render,以提升性能。
在這個過程中勢必要用到React Native和html頁面之間的通信,這里分享一下

React Native向html頁面發送消息:

  1. react native頁面
import React, {Component} from 'react';
 import {
   View,
 } from 'react-native';
 import {WebView} from 'react-native-webview';

 export default class Demo extends Component {
   constructor(props) {
     super(props);
     this.state = {
       info: null,
     };
   }
 
   render() {
     const that = this;
     return (
      <View>
        <WebView
          ref={webview => {
            that.webview = webview;
          }}
          source={require('./index.html')}
          javaScriptEnabled={true}
          allowUniversalAccessFromFileURLs={true}
          allowFileAccess={true}
          originWhitelist={['*']}
          onMessage={e => {
            this.handleMessage(e);
          }}
          onLoadStart={() => {}}
          onError={e => {
            global.Toast(e.message);
          }}
        />
    </View>
     );
   }
   // 向html發送消息
   postMessage(data) {
     const script = "window.onMessage('" + data + "')";
     try {
       this.webview.injectJavaScript(script);
     } catch (e) {
       setTimeout(() => {
         this.postMessage(data);
       }, 2000);
     }
   }
 
   // 接收html消息并處理
   handleMessage(e) {
     try {
       let data = global.JParse(e.nativeEvent.data);
       console.log(data);
     } catch (e) {
       console.warn(e);
     }
   }

 }

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
    />
</head>
<body>
<script>
    //發送消息給RN
    function postMessage(data) {
      window.ReactNativeWebView.postMessage(data)
    }

    //處理RN傳過來的消息
    window.onMessage = function(msgStr) {
      try {
        var msg = JSON.parse(msgStr)
        } catch (e) {
          alert(e.message);
        }
      }
</script>
</body>
</html>
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容