DeviceEventEmitter React-Native 发送和接受消息(事件监听器)
A页面注册通知:
import {DeviceEventEmitter} from 'react-native'; //… //调用事件通知 DeviceEventEmitter.emit('xxxName',param); //xxxName:通知的名称 param:发送的消息(传参)
B页面接收通知:
componentDidMount(){ var self = this; this.listener =DeviceEventEmitter.addListener('xxxName',function(param){ // use param do something }); } //xxxName:通知的名称 param:接收到的消息(传参) componentWillUnmount(){ this.listener.remove(); } //在componentWillUnmount 内需要我们手动移除通知
我的页面在获取到用户数据后:
//注册监听事件,时间名称:changeMine 传参:jsonData.avatar(头像url) DeviceEventEmitter.emit('changeMine',jsonData.avatar);
tabbar.js文件
componentDidMount(){ var self = this; this.listener = DeviceEventEmitter.addListener('changeMine',function(url){ self.setState({ avatar:url }) }); //通知开始,获取到url,调用setState 方法,刷新状态机,这时候实时的刷新了‘我的’图标 //最后别忘了移除通知 componentWillUnmount(){ this.listener.remove(); }
使用实例:
1. 点击底部按钮 触发分享朋友圈 / 下载海报图片(包括二维码)
//触发 _share(type = undefined) { if (this.props.type === 'letter') { DeviceEventEmitter.emit('_getSharePage', type); //全局注册分享事件 } } <Button onPress={() => { this._share('wechat') }} title={分享到微信} /> <Button onPress={() => { this._share('save') }} title={下载海报} />
调用
import ViewShot, {captureRef} from "react-native-view-shot"; //将React Native视图捕获到图像。
import QRCode from 'react-native-qrcode-svg'; //将React Native图片生成二维码
import CameraRoll from "@react-native-community/cameraroll"; //这里需要pod很多个文件
import {check, PERMISSIONS, RESULTS} from 'react-native-permissions'; //获取手机权限
componentDidMount() { // Toast.hide(); this.listener = DeviceEventEmitter.addListener('_getSharePage', (params) => { captureRef(this.refs.viewShot, { //通过 ViewShot 绑定的ref来设置截图的类型大小格式 format: "jpg", quality: 1.0, result: 'tmpfile', // snapshotContentContainer:true }).then( uri => { //uri就是返回的图片地址 switch (params) { case 'qq': break; case 'wechat': let message = { platform: "wechat_session", type: 'image', imagePath: uri }; JShareModule.share(message, (map) => { if (map.state === 'success') { // Toast.message('分享成功') } }, (map) => { Toast.message('请安装微信后尝试') // console.log("share failed, map: " + map); }) break; case 'pyq': let wechat = { platform: "wechat_timeLine", type: 'image', imagePath: uri }; JShareModule.share(wechat, (map) => { // Toast.message('分享成功') }, (map) => { Toast.message('取消分享') }) break; case 'weibo': break; default: // if(!this.state.select){ // Toast.message('请选择封面图') // return; // } if (Platform.OS === 'ios') { check(PERMISSIONS.IOS.PHOTO_LIBRARY).then(response => { // if (response === 'authorized') { // } else { // Toast.message('保存相片的权限没开启,请在iPhone的“设置-隐私”选项中,允许修改您的相册') // } switch (response) { case RESULTS.UNAVAILABLE: console.log( 'This feature is not available (on this device / in this context)', ); break; case RESULTS.DENIED: console.log( 'The permission has not been requested / is denied but requestable', ); break; case RESULTS.GRANTED: console.log('The permission is granted'); CameraRoll.saveToCameraRoll(uri,'photo').then(res => { Toast.message('邀请好友截图保存成功'); }).catch(err => { Toast.message(err); }) break; case RESULTS.BLOCKED: console.log('The permission is denied and not requestable anymore'); break; } }).catch(err => { console.log('看看错误是什么',err); Toast.message('有错误找原因') }) } else { try { PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE ).then(granted => { if (granted === PermissionsAndroid.RESULTS.GRANTED) { CameraRoll.saveToCameraRoll(uri, 'photo').then(res => { Toast.message('邀请好友截图保存成功'); }).catch(err => { Toast.message(err); }) } else { Toast.message('保存失败, 请授予权限'); } }).catch(err => { Toast.message('保存失败, 请授予权限'); }) } catch (err) { Toast.message('保存失败, 请授予权限'); } } break; } }, error => { Toast.message(error); } ).catch(err => { console.log(err); }); }) }
<ViewShot ref="viewShot" >
<QRCode
value={Config.domain + '/web/register?invite_code=' + this.props.inviteCode}
size={168}
bgColor='#000'
fgColor='white'
/>
</ViewShot>
监听上拉加载事件
A 父
componentDidMount(){ let self = this; this.listener =DeviceEventEmitter.addListener('footerRefresh',function(func){ self.refreshTrade = func }); } componentWillUnmount(){ this.listener.remove(); } //当触发上拉加载的时候 this.refreshTrade && this.refreshTrade()
B 子
getOrderList(clean = false,use = true) { this.setState({loading: true}); Http.post('/api/v1/ok/spot/orders', { pers: 10, page: clean ? 1 : this.state.page + 1, }).then(res => { this.setState({loading: false}); if (res.status === 10000) { //防止监听器一直触发,保持子页面在父页面只有一个监听器 if(use){ DeviceEventEmitter.emit('footerRefresh',res.has_next ? ()=>{this.getOrderList(false,false)} : ()=>{}); } this.setState({ trade: clean ? res.data : this.state.trade.concat(res.data), hasNext: res.has_next, page: res.page, }); } }).catch(err => { console.log(err); Toast.message('通讯失败'); }); }