We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
首先需要项目中安装events包
npm install events --save
在src下新建一个util目录里面建一个events.js
events.js
import { EventEmitter } from 'events'; export default new EventEmitter();
原理是使用events模块的自定义事件机制
events
在componentDidMount事件中,如果组件挂载完成,再订阅事件;在组件卸载的时候,在componentWillUnmount事件中取消事件的订阅; 以常用的发布/订阅模式举例,借用Node.js Events模块的浏览器版实现
在一个组件的componentDidMount生命周期中中监听事件,并在componentWillUnmount生命周期中销毁
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中组件通信的几种方式
The text was updated successfully, but these errors were encountered:
No branches or pull requests
安装
首先需要项目中安装events包
在src下新建一个util目录里面建一个
events.js
使用
原理是使用
events
模块的自定义事件机制在一个组件的
componentDidMount
生命周期中中监听事件,并在componentWillUnmount
生命周期中销毁然后在另外一个组件中触发该事件
参考文档
React中组件通信的几种方式
The text was updated successfully, but these errors were encountered: