// 下载插件
yarn add pubsub-js
import React, { Component } from 'react'
import PubSub from 'pubsub-js' // 引入插件
export default class Await extends Component {
componentDidMount(){
/* 通过subscribe 订阅消息 有两个参数
参1 订阅的消息名 同发布一个
参2 函数 函数参数有两个 顺序为当前通讯名、传递的参数
组件销毁时将通信终止 就跟计时器一个意思, 所以将此实例保存
*/
this.token = PubSub.subscribe('Hello_Brother', (_,data)=>{
console.log(data) // 兄弟 今晚857
})
}
componentWillUnmount(){
// 组件销毁时将通信终止
PubSub.unsubscribe(this.token)
}
render() {
return (
<div>
a组件
</div>
)
}
}
import React, { Component } from 'react'
import PubSub from 'pubsub-js'
export default class Send extends Component {
send = ()=> {
PubSub.publish('Hello_Brother', '兄弟 今晚857')
}
render() {
return (
<div>
<button onClick={this.send}>约兄弟喝酒</button>
</div>
)
}
}