使用 react-native-webview-bridge 三方库遇到的问题

注明:在Android上运行时,inject的js一定要严格准守js语法,语句结尾一定要记得添加分号结尾,而且不要带有// 这类注释,具体原因不明,从表现上看,估计是会改变inject进去的js 排列,应该是被缩进或者换行被删除了,所以带有双斜杠的注释,以及语句结尾没有分号的都会出现注入后没法正确使用注入的js。

1.在github上将该三方插件集成到自己项目中,具体参考:https://github.com/alinz/react-native-webview-bridge

在个人当前试用版会导致不兼容,修改:node_modules\react-native-webview-bridge\webview-bridge\index.android.js 头部:


import React, { Component } from 'react';
var invariant = require('invariant');
var keyMirror = require('keymirror');
var merge = require('merge');
var resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource');
var {PropTypes} = React;
var {
  ActivityIndicatorIOS,
      EdgeInsetsPropType,
      StyleSheet,
      Text,
      View,
      WebView,
      requireNativeComponent,
      UIManager,
      DeviceEventEmitter,
      NativeModules: {
          WebViewBridgeManager
      },
  findNodeHandle,
}  = require('react-native');


并且将:  将一下代码中的React.findNodeHandle删除开头的React,,更改为:  return findNodeHandle(this.refs[RCT_WEBVIEWBRIDGE_REF]);

getWebViewBridgeHandle: function() {
    return React.findNodeHandle(this.refs[RCT_WEBVIEWBRIDGE_REF]);
  }


在Android 中是只有一个实例的,也就是说在一个<webbridge>中调用了injectedJavaScript,则,其余不会再对其响应的界面进行注入message相关的语句,导致,页面无法同native进行通信,更改源码:使得能够注入多个页面,详细代码如下网址已实现该问题处理:

https://github.com/alinz/react-native-webview-bridge/pull/106/files#r67672790


最后一个严重的问题是,当实现了多个实例后,当react-native 中unmount了组件,再重新进入组件,会发现,webview中仅仅往react-native的组件发了一条消息,但是在react-native中出现多次响应,


查看源码发现:node_modules\react-native-webview-bridge\webview-bridge\index.android.js,源码中发现只有addListener,而没有remove.Listener:从而导致,unmount的组件再进去后,listener保留在运行过程中,也就是出现多个相同的listener,这样webview往react-native组件发一个消息,而导致多次响应。

解决方法:将listener通过变量记录,在componentWillUnmount中将其移除,避免出现多次接收webview组件的消息:

添加一个变量listener:

var WebViewBridge = React.createClass({
  listener:null,
  propTypes: {
    ...WebView.propTypes,


    /**
     * Will be called once the message is being sent from webview
     */
    onBridgeMessage: PropTypes.func,
  },


将listener实例赋值给该变量:

this.listener=DeviceEventEmitter.addListener("webViewBridgeMessage", (body) => {
      const { onBridgeMessage } = this.props;
      const message = body.message;
      if (onBridgeMessage) {
        onBridgeMessage(message);
      }
    });


添加一个方法生命周期的方法销毁这个监听:

componentWillUnmount:function(){
    this.listener.remove();
    this.listener=null;
  }


猜你喜欢

转载自blog.csdn.net/qq_21937107/article/details/84987049
今日推荐