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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
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

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.

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

React's Ecosystem: Libraries, Tools, and Best Practices React's Ecosystem: Libraries, Tools, and Best Practices Apr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

H5 Code: Accessibility and Semantic HTML H5 Code: Accessibility and Semantic HTML Apr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5? Is h5 same as HTML5? Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

See all articles