1、events的使用
需要使用命令添加events库 yarn add events
1、初始化实例对象const events = new EventEmitter()
2、添加事件监听events. addListener("events_name", this.handleEventMessage);
3、移除事件监听events.removeListener("events_name", this.handleEventMessage);
import React, { PureComponent } from 'react'
import {EventEmitter} from 'events'
const events = new EventEmitter()
class Home extends PureComponent {
constructor(props) {
super(props);
}
componentDidMount() {
events.addListener("sayHello", this.handleEventMessage);
}
componentWillUnmount() {
events.removeListener("sayHello", this.handleEventMessage);
}
render() {
return (
<div>
Profile
</div>
)
}
handleEventMessage(args) {
console.log(args + "hello");
}
}
class Profile extends PureComponent {
render() {
return (
<div>
Profile
<button onClick={e =>this.sendEvent()}>点击发送消息</button>
</div>
)
}
sendEvent() {
console.log("发送消息")
events.emit("sayHello", "123");
}
}
export default class App extends PureComponent {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Profile />
<Home />
</div>
)
}
}
网友评论