深入浅析React Native与web的基本交互附代码

之前的文章《教你怎么使用css3给图片添加渐变效果(代码详解)》中,给大家介绍怎么使用css3给图片添加渐变效果。下面本篇文章给大家介绍一下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
};
<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 />;
  }}
/>;

H5和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>

注意事项

假如你的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 <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({
        '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视频教程

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: 首先在编辑器里面插入javascript代码: 确定后会在编辑器插入这样的代码: <pre
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换为SyntaxHighlighter代码高亮插件 上一篇“让kindeditor显示高亮代码”中已经
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)
原生JS实现别踩白块小游戏(一)