Table of Contents
Interaction between H5 and React Native
Notes
Native call H5 method
H5 call native method
Home Web Front-end JS Tutorial 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)

Aug 17, 2021 am 11:04 AM
h5 js react

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 />;
  }}
/>;
Copy after login

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>
Copy after login

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";
Copy after login

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);
    }
}];
Copy after login

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();
Copy after login

Prompt error:

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to implement h5 to slide up on the web side to load the next page How to implement h5 to slide up on the web side to load the next page Mar 11, 2024 am 10:26 AM

Implementation steps: 1. Monitor the scroll event of the page; 2. Determine whether the page has scrolled to the bottom; 3. Load the next page of data; 4. Update the page scroll position.

See all articles