react组件之间的事件监听

623 阅读1分钟

react组件之间的事件监听

  1. 定义事件bus
class EventBus {
    constructor() {
        this.cache = {}
    }
    on(name, func) {
        if (this.cache[name]) {
            this.cache[name].push(func)
        } else {
            this.cache[name] = [func]
        }
    }
    emit(name, params) {
        if (this.cache[name]) {
            const tasks = this.cache[name].slice()
            for (const func of tasks) {
                func(params)
            }
        }
    }
    off(name, func) {
        let tasks = this.cache[name]
        if (tasks) {
            const index = tasks.findIndex(fn => fn === func)
            if (index > 0) {
                tasks.splice(index, 1)
            } else {
                delete this.cache[name]
            }
        }
    }
}

const eventBus = new EventBus()
export default eventBus
  1. 在这几个组件的共同父组件中传入eventBus对象
    <div className = 'parent' eventBus={eventBus}>
    ....
    </div>
  1. 子组件A监听事件
this.props.eventBus.on('submit', ()=>{}); 

4.子组件B触发事件

this.props.eventBus.emit('submit');