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利用events模块实现组件通信 #14

Open
Wscats opened this issue Jul 5, 2018 · 0 comments
Open

React利用events模块实现组件通信 #14

Wscats opened this issue Jul 5, 2018 · 0 comments

Comments

@Wscats
Copy link
Owner

Wscats commented Jul 5, 2018

安装

首先需要项目中安装events

npm install events --save

image

在src下新建一个util目录里面建一个events.js

import { EventEmitter } from 'events';
export default new EventEmitter();

image

使用

原理是使用events模块的自定义事件机制

componentDidMount事件中,如果组件挂载完成,再订阅事件;在组件卸载的时候,在componentWillUnmount事件中取消事件的订阅;
以常用的发布/订阅模式举例,借用Node.js Events模块的浏览器版实现

在一个组件的componentDidMount生命周期中中监听事件,并在componentWillUnmount生命周期中销毁

import emitter from '../../util/events';
componentDidMount() {
	// 组件装载完成以后声明一个自定义事件
	this.eventEmitter = emitter.addListener('changeMessage', (message) => {
		this.setState({
			message,
		});
	});
}
componentWillUnmount() {
	emitter.removeListener(this.eventEmitter);
}

然后在另外一个组件中触发该事件

import emitter from '../../util/events';
changeMessage() {
	emitter.emit('changeMessage', 'wscats');
}

参考文档

React中组件通信的几种方式

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