React主要使用pubsub-js 插件管理消息订阅和发布 ,适用任一组件通信。
1.下载 yarn add pubsub-js
2.使用 import PubSub from ‘pubsub-js‘
⒈在接收组件定义消息名
//在接收消息组件的ComponentDidMount生命周期定义
this.token = PubSub.subscribe(‘自定义消息名‘,(_,data)=>{
//data就是接收到的消息 ,消息通过 PubSub.publish(‘消息名‘,数据)发送
})
//在接收消息组件的ComponentWillUnmount生命周期定义
PubSub.unsubscribe(this.token)
⒉在发送组件定义发送
PubSub.publish(‘消息名‘,data);
原文:https://www.cnblogs.com/suntongjian/p/14738176.html