react组件通信方式总结

1.props和事件

2.Evnentbus

class EventBus {
  constructor() {
    this.events = this.events || new Object(); 
  }
}
//首先构造函数需要存储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[0].apply(this, args);  
         }  
   };
 //然后我们需要写监听函数,参数是事件type和触发时需要执行的回调函数
 EventBus.prototype.addListener = function(type, fun) { 
       const e = this.events[type]; 

        if (!e) {   //如果从未注册过监听函数,则将函数放入数组存入对应的键名下
         this.events[type]= [fun];
        } else {  //如果注册过,则直接放入
           e.push(fun);
        }
  };// 移除监听

EventBus.prototype.removeListener = function (type, fn) {
  const handler = this._events.get(type); // 获取对应事件名称的函数清单
  // 如果是函数,说明只被监听了一次
  if (handler && typeof handler === ‘function‘) {
    this._events.delete(type, fn);
  } else {
    let postion;
    // 如果handler是数组,说明被监听多次要找到对应的函数
    for (let i = 0; i < handler.length; i++) {
      if (handler[i] === fn) {
        postion = i;
      } else {
        postion = -1;
      }
    }
    // 如果找到匹配的函数,从数组中清除
    if (postion !== -1) {
      // 找到数组对应的位置,直接清除此回调
      handler.splice(postion, 1);
      // 如果清除后只有一个函数,那么取消数组,以函数形式保存
      if (handler.length === 1) {
        this._events.set(type, handler[0]);
      }
    } else {
      return this;
    }
  }
};


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

然后,我们在login组件中加入

EventBus.emit(‘login‘,values.userName)

在需要监听的组件加入

EventBus.addListener(‘login‘,(name)=>{
            this.setState({user:name})
        })

3.redux

4.context