react-native-webview-bus
让 React Native 与 webview 页面互通的 Event bus,帮助快速实现 Hybrid 应用
Install
npm install react-native-webview-bus --save
Api
- WebviewBus:WebviewBus 类,var webviewBus = new WebviewBus(window or webview)
- webviewBus.on(event, handler):添加跨端的事件监听器,如 web 端调用则监听 native 端发送的事件,反之亦然
- webviewBus.once(event, handler):添加跨端的单次事件监听器,同 webviewBus.on
- webviewBus.off(event, handler):取消跨端的事件监听器
- webviewBus.emit(event, data):触发跨端事件,如 web 端调用则 native 触发对应事件
Usage
React Native 端组件
// App.js;type Props = {}<Props>{superpropsthisstate =title: '分享收客'url: 'https://crm.demo.keketour.com/test.html'}/*** 组件生命周期事件 componentDidMount*/{// 创建 WebviewBus 实例thiswebviewBus = thisrefswebview// 监听 webview 页面发出的事件thiswebviewBusthiswebviewBus}/*** 返回*/{thiswebviewBus}/*** 设置标题* @param*/{this}/*** 分享朋友圈* @param*/{}// Code example to share text message:trylet result = await WeChat;console;catch eif e instanceof WeChatWechatErrorconsole;elsethrow e;/*** 渲染组件*/{return<View style=stylescontainer><View style=stylesheader><Button style=stylesback onPress=thisgoBack>返回</Button><Text style=stylestitle>thisstatetitle</Text></View><WebViewref="webview"style=styleswebviewsource=uri: thisstateurl method: 'GET'javaScriptEnableddomStorageEnabledthirdPartyCookiesEnabledmixedContentMode="always"bounces=falseinitialScale=100decelerationRate="normal"onMessage=thisonMessageonShouldStartLoadWithRequest=thisonShouldStartLoadWithRequestonNavigationStateChange=thisonNavigationStateChangeautomaticallyAdjustContentInsets=false></WebView></View>;}
web 端页面(以 Vue 页面为例)
<template><section><button @click="setTitle">更改标题</button><button @click="shareToTimeline">分享到朋友圈</button></section></template><script>{return}{// 创建 WebviewBus 实例thiswebviewBus = window// 监听 Native 的 back 事件thiswebviewBus}methods:/*** 设置 Native 标题*/{thiswebviewBus}/*** 调用 Native 分享到朋友圈*/{thiswebviewBus}</script>