我主要使用 Vue,最近才开始使用 React。到目前为止很喜欢它,它在很多方面与 Vue 非常相似,这使得学习它变得更加容易。
现在,让我们考虑两个兄弟组件。当第二个组件发生某些事情时,我想触发第一个组件中的某些内容。在 Vue 中,您只需绑定(bind) window.bus = new Vue
,然后在组件之一 bus.$emit('event')
中发出并在 中绑定(bind)>第二个组件
。bus.$on('event', this.doSth)
的 >mounted()
如何在 React 中实现这一点?
最佳答案
Event Bus只是一个全局函数寄存器,你能用吗
class _EventBus {
constructor() {
this.bus = {};
}
$off(id) {
delete this.bus[id];
}
$on(id, callback) {
this.bus[id] = callback;
}
$emit(id, ...params) {
if(this.bus[id])
this.bus[id](...params);
}
}
export const EventBus = new _EventBus();
export const
防止多个实例,使类静态
关于javascript - React 中的事件总线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53329773/