react EventBus事件总线传参
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在React中,EventBus或者可以理解为自定义事件系统,可以用于组件间通信。以下是一个简单的例子,展示了如何使用EventBus传递参数:
import React from 'react';
// 创建一个简单的Event Bus
const EventBus = {
listeners: {},
on(event, callback) {
this.listeners[event] = this.listeners[event] || [];
this.listeners[event].push(callback);
},
emit(event, ...args) {
if (this.listeners[event]) {
this.listeners[event].forEach(callback => callback(...args));
}
}
};
// 使用EventBus的组件
class ComponentA extends React.Component {
notifyB = (message) => {
EventBus.emit('ComponentAEvent', message);
};
render() {
return (
<div>
<button onClick={() => this.notifyB('Hello from Component A!')}>
Notify Component B
</button>
</div>
);
}
}
class ComponentB extends React.Component {
componentDidMount() {
EventBus.on('ComponentAEvent', this.handleEventFromA);
}
componentWillUnmount() {
EventBus.on('ComponentAEvent', this.handleEventFromA);
}
handleEventFromA = (message) => {
alert(`Event received in Component B with message: ${message}`);
};
render() {
return <div>Component B is listening for events</div>;
}
}
// 应用组件
const App = () => (
<>
<ComponentA />
<ComponentB />
</>
);
export default App;
在这个例子中,我们定义了一个简单的EventBus
对象,它有on
方法用于监听事件,emit
方法用于触发事件,并传递参数。ComponentA
有一个按钮,当点击时,它会通过EventBus
发送一个事件及消息给ComponentB
。ComponentB
在挂载时开始监听ComponentA
发出的事件,并处理接收到的消息。
评论已关闭