ReactNative学习笔记

RN EventBus实现跨组件间通信

2019-04-25  本文已影响0人  奔跑的杰尼龟zxl

写在前面

虽然有一定的移动APP开发经验,但RN技术我还是一个小白,上一篇对路由等有了一定的了解,这篇文章将着重解决RN跨组件进行通信的方式。实现的效果是,A界面跳转B界面,B界面进行状态的修改,然后A界面做出相应的数值变化。

效果展示

// 进入界面A
监听界面:componentWillMount
进行监听
// 进入界面B并发布消息
界面监听回传值 传递数值
// 退出界面A
监听界面:componentWillUnmount
取消监听

ok就是如上日志的效果,生命周期开始注册,然后结束的时候取消监听即可

EventBus源码

class EventBus {
    constructor() {
        this.events = this.events || {};
    }
}

//构造函数需要存储event事件
//发布事件,参数是事件的type和需要传递的参数
EventBus.prototype.emit = function (type, ...args) {
    let e;
    e = this.events[type];
    // 查看这个type的event有多少个回调函数,如果有多个需要依次调用。
    if (Array.isArray(e)) {
        for (let i = 0; i < e.length; i++) {
            e[i].apply(this, args);
        }
    } else {
        e.apply(this, args);
    }
};

//监听函数,参数是事件type和触发时需要执行的回调函数
EventBus.prototype.addListener = function (type, fun) {
    const e = this.events[type];
    let currentIndex = -1
    if (!e) {   //如果从未注册过监听函数,则将函数放入数组存入对应的键名下
        this.events[type] = [fun];
        currentIndex = 0
    } else {  //如果注册过,则直接放入
        e.push(fun);
        //获取当前组件监听函数,在观察函数数组中的索引,移除监听时使用
        currentIndex = this.events[type].length - 1
    }
    return { type, index: currentIndex}
};


//移除监听
EventBus.prototype.remove = function (subscribe) {
    let { type, index } = subscribe
    let e;
    e = this.events[type];
    // 查看这个type的event有多少个回调函数,如果有多个需要依次调用。
    if (Array.isArray(e)) {
        //监听的函数为空,则空处理
        if (e.length === 0) {
            return
        } else if (e.length === 1) {
            //只有一个监听的函数,则直接移除监听
            e.splice(0, 1)
        } else {
            //如果同一个key存在多个监听函数,只移除当前组件监听函数
            for (let i = 0; i < e.length; i++) {
                if (index > 0 && i === index) {
                    e.splice(index, 1)
                }
            }
        }
    } else {
        e = []
    }
};

//移除所有监听
EventBus.prototype.removeAll = function () {
    //移除所有监听函数
    if (this.events.length > 0) {
        this.events.length = 0;
    }
};

const eventBus = new EventBus();
export default eventBus;

具体代码使用

PageA 进行注册

               // 监听并设置状态改变刚更新UI 
        componentWillMount(): void {
            console.log('监听界面:componentWillMount');
            console.log('进行监听');
            this.subscribe = EventBus.addListener("notify", data => {
                console.log("界面监听回传值", data);
                this.setState({
                    show:data
                })
            });
        }
                // 取消监听以放置重复注册
        componentWillUnmount(): void {
            console.log('监听界面:componentWillUnmount');
            console.log('取消监听');
            EventBus.remove(this.subscribe);
        }

PageB触发

EventBus.emit('notify','传递数值');

好了如上就是全部的使用了

拓展

由于受了Android开发的影响,始终对EventBus情有独钟,应用vue也是如此,但我们也需要对其基本的父子组件通信的学习以及了解,如props等父子通信是要会的。这是我们通信学习的第一步,后面还需要对redux进行深入的学习。既然开始了,就一定要百分百的付出。

参考文章

React组件通信——Event Bus
React Native Event Bus,消息总线
React Native组件生命周期

上一篇 下一篇

猜你喜欢

热点阅读