Home  >  Article  >  Web Front-end  >  An in-depth analysis of the basic interaction between React Native and the web (with code)

An in-depth analysis of the basic interaction between React Native and the web (with code)

奋力向前
奋力向前forward
2021-08-17 11:04:533712browse

In the previous article "Teach you how to use css3 to add gradient effects to images (detailed code explanation)", I introduced how to use css3 to add gradient effects to images. The following article will introduce you to the basic interaction between React Native and the web. It has certain reference value and friends in need can refer to it.

Interaction between React Native and H5

//接收来自H5的消息
onMessage = (e) => {
  Log("WebView onMessage 收到H5参数:", e.nativeEvent.data);
  let params = e.nativeEvent.data;
  params = JSON.parse(params);
  Log("WebView onMessage 收到H5参数 json后:", params);
};

onLoadEnd = (e) => {
  Log("WebView onLoadEnd e:", e.nativeEvent);
  let data = {
    source: "from rn",
  };
  this.web && this.web.postMessage(JSON.stringify(data)); //发送消息到H5
};
<WebView
  ref={(webview) => {
    this.web = webview;
  }}
  style={{
    width: "100%",
    height: "100%",
    justifyContent: "center",
    alignItems: "center",
  }}
  source={require("../data/testwebview.html")}
  onLoadEnd={this.onLoadEnd} //加载成功或者失败都会回调
  onMessage={(e) => this.onMessage(e)}
  javaScriptEnabled={true} //指定WebView中是否启用JavaScript
  startInLoadingState={true} //强制WebView在第一次加载时先显示loading视图
  renderError={(e) => {
    return <View />;
  }}
/>;

Interaction between H5 and React Native

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>text webview</title>
    <script type="application/javascript">
      //相互通信只能传递字符串类型
      function test() {
        //发送消息到rn
        let params = {
          msg: "h5 to rn",
          source: "H5",
        };
        window.postMessage(JSON.stringify(params)); //发送消息到rn
      }

      window.document.addEventListener("message", function (e) {
        //注册事件 接收数据
        const message = e.data; //字符串类型
        console.log("WebView message:", message);
        window.postMessage(message);
      });
    </script>
  </head>
  <body>
    <h1>chuchur</h1>
    <button onclick="test()">单击</button>
  </body>
</html>

Notes

If your WebView is quoted from react-native. H5To send a message to RN, use window.postMessage(message)In order to reduce the surface area of ​​React Native, it will be removed from React Native is deleted from the core, it is recommended to use

import { WebView } from "react-native"; //会被移除
//to
import { WebView } from "react-native-webview";

If it is introduced with react-native-webview, the communication method is window.ReactNativeWebView.postMessage(message)

For more information, please read the proposals at https://github.com/react-native-community/discussions-and-proposals/issues/6.

Native call H5 method

[wkWebView evaluateJavaScript:@"js方法名()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
    if (!error) { // 成功
       NSLog(@"%@",response);
    } else { // 失败
        NSLog(@"%@",error.localizedDescription);
    }
}];

H5 call native method

 //App端:
  // 1. WKWebView注入ScriptMessageHandler
 [wkWebView.configuration.userContentController addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:@"xxx"];
  // 2. 提供setWebViewAppearance方法,这样就能反射出H5即将传来的字符串@"setWebViewAppearance"
  - (void)setWebViewAppearance {

  }

//H5端:
  // 1. 获取handler
  var handler = {
    callHander: function (json) {
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {//ios
        window.webkit.messageHandlers.xxx.postMessage(JSON.stringify(json))
    }
    if (/(Android)/i.test(navigator.userAgent)) { //Android
        window.xxx.postMessage(JSON.stringify(json));
    }
  }
  // 2. 设置调用App方法所需要的传出的参数(这里是json格式)
  function setAppAppearance(){
    handler.callHander({
        &#39;body&#39;:"setWebViewAppearance",
        &#39;buttons&#39;: [
            {
                "text":"分享",
                "action":""
            }
        ],
        &#39;title&#39;:"这是webView的标题"
    });
  }
  // 3. H5调用自己的设置方法,继而调用了原生客户端的方法
  setAppAppearance();

Prompt error:

WKJavaScriptExceptionMessage=ReferenceError: Can&#39;t find variable xxx
需要方法需要挂在 window 上 window.xxx = function() {}
for vue, mounted: window.xxx =this.xxx

Recommended learning: React video tutorial

The above is the detailed content of An in-depth analysis of the basic interaction between React Native and the web (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:chuchur.com. If there is any infringement, please contact admin@php.cn delete