我正在try 使用onMessage侦听器.该网站正在执行postMessage(window.postMessage("Post message from web");),但react native的webview onMessage listener没有执行任何操作!我不知道我做错了什么.

这是HTML

<script type="text/javascript">
  window.postMessage("Post message from web");
</script>

下面是react-native 代码:

  <WebView
    ref={( webView ) => this.webView = webView}
    onMessage={this.onMessage}
    source={{uri: 'https://app.sodge.co/login/response.html'}}
  />

onMessage react-native 函数:

onMessage( event ) {
  Alert.alert(
    'On Message',
    event.nativeEvent.data,
    [
      {text: 'OK'},
    ],
    { cancelable: true }
  )
}

这里还有expo 小吃...我不知道我做错了...

推荐答案

根据this issue,您需要等到React Native postMessage替换了Native window.postMessage(不要问我why他们正在替换一个本机函数,而不是创建一个新函数).

一种解决方案是采取以下措施:

function waitForBridge() {

   //the react native postMessage has only 1 parameter
   //while the default one has 2, so check the signature
   //of the function

   if (window.postMessage.length !== 1){
     setTimeout(waitForBridge, 200);
   }
   else {
     window.postMessage('abc');
   }
}

window.onload = waitForBridge;

React-native相关问答推荐

出现错误:使用 process(css).then(cb) 来使用异步插件

构建 iOS Expo 应用时出现 React-Native xcodebuild 错误 65

我们应该在 react-native 移动应用程序中使用哪个图标库

React Native - 动画宽度缩小

你使用 react native 应该学习 react.js 吗?

警告:API 'variant.getMergeAssets()' 已过时 / Android Studio 3.3

使用react native获取设备令牌

在 react-native 元素中更改 android 和 ios 的入口文件路径

React-Native Android - 找不到 com.android.tools:common

在 Docker 中使用 Fastlane 构建 iOS 应用

词法或预处理器问题 - 未找到 event2/event-config.h 文件

react-native android应用程序中的underlineColorAndroid is not a valid style property错误

渲染时获取未定义不是 React Native 中的对象

ScrollView bounce的 2 种不同背景 colored颜色

将 React Native 升级到 0.60-RC2 后找不到库libjsc.so

无法在react-native元素中扩展 Zip

如何在 react native 中将数组保存在异步存储中?

降级 react-native 的适当机制

react-native图像预取

React-Native 水平滚动视图分页:预览下一页/卡片