资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

ReactNative与web的基本交互方式

本篇内容介绍了“React Native与web的基本交互方式”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

创新互联专注于景东企业网站建设,响应式网站建设,商城建设。景东网站建设公司,为景东等地区提供建站服务。全流程按需搭建网站,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务

React Native和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
};
 {
    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 ;
  }}
/>;

H5和React Native交互



  
    
    text webview
    
      //相互通信只能传递字符串类型
      function test() {
        //发送消息到rn
        let params = {
          msg: "h6 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);
      });
    
  
  
    

chuchur

    单击   

注意事项

假如你的WebView是从react-native里引用的话。H5RN发消息则使用window.postMessage(message)为了减少React Native的表面积,将从React Native核心中删除,推荐使用

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

假如是用react-native-webview引入则通讯方式使用window.ReactNativeWebView.postMessage(message)

有关更多信息,请阅读地址https://github.com/react-native-community/discussions-and-proposals/issues/6提案。

原生调用 H5 方法

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

H5 调用原生方法

 //App端:
  // 1. WKWebView注入ScriptMessageHandler
 [wkWebView.configuration.userContentController addScriptMessageHandler:(id )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({
        'body':"setWebViewAppearance",
        'buttons': [
            {
                "text":"分享",
                "action":""
            }
        ],
        'title':"这是webView的标题"
    });
  }
  // 3. H5调用自己的设置方法,继而调用了原生客户端的方法
  setAppAppearance();

提示报错:

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

“React Native与web的基本交互方式”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


本文名称:ReactNative与web的基本交互方式
当前链接:http://cdkjz.cn/article/gdshds.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220