Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React - 兄弟组件通信 #38

Open
jtwang7 opened this issue Dec 10, 2021 · 0 comments
Open

React - 兄弟组件通信 #38

jtwang7 opened this issue Dec 10, 2021 · 0 comments

Comments

@jtwang7
Copy link
Owner

jtwang7 commented Dec 10, 2021

React - 兄弟组件通信

使用 events 包实现 React 兄弟组件间的简单通信:

npm install events --save

npm 包地址:events(npm)
使用文档:nodejs-events

Step 1

新建一个 js 文件作为 EventBus。在该文件中,引入 events 包,并实例化一个事件对象并向外暴露接口,供通信时使用。

// eventBus.js
import { EventEmitter } from 'events';
export default new EventEmitter();

Step 2

注册监听事件:

// 兄弟组件1
import Bus from './eventBus';

Bus.on('xxx', (payload) => {console.log(payload)});

Step 3

触发事件监听 (事件发送):

// 兄弟组件2
import Bus from './eventBus';

Bus.emit('xxx', payload)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant