我们在使用react或者vue开发时,特别是大项目的开发过程中,为了使代码更好的得到复用,会大量的使用组件,但是组件之间的消息传输不是很方便。然后我就找到了这个pubsub-js来实现组件之间的通信。
安装插件:
npm install --save pubsub-js
用法
发送消息(发布方可传给多个订阅方)
//作为发布方 把消息发送到名为newNumber的订阅方 可传给多个订阅方
PubSub.publish('newNumber',this.state.no)
接收消息(订阅方):
//订阅方监听
PubSub.subscribe('newNumber',(message,data)=>{
console.log(message,data)
});
为了突显插件的功能,我这里在简单写个页面,然后在主页面中引入两个组件,下面是实测图和代码
实测图
源代码
import React from 'react';
import {Page,} from 'framework7-react';
import PubSub from "pubsub-js";
import ItemOne from "./item-one";
import ItemTwo from "./item-two";
export default class PubSubMain extends React.Component{
constructor(props){
super(props);
this.state = {
no:0
}
}
//点击按钮数字加一
handleOnBtnClick(){
this.setState({
no:++this.state.no
},()=>{
//作为 把消息发送到名为newNumber的接收方
PubSub.publish('newNumber',this.state.no)
})
}
render() {
return <Page>
<div style={{display:"flex",marginTop:10}}>
<ItemOne/>
<ItemTwo/>
</div>
<button style={{width:'90%',marginLeft:'5%',marginTop:10,height:30}}
onClick={()=>this.handleOnBtnClick()}>{'点击数字加 1'}</button>
</Page>
}
}
组件页面:
import React from 'react';
import PubSub from "pubsub-js";
export default class ItemOne extends React.Component{
constructor(props){
super(props);
this.state = {
index:0
}
}
//在组件挂载之后立刻监听
componentDidMount() {
PubSub.subscribe('newNumber',(message,data)=>{
console.log(message,data)
//监听到消息之后刷新数据
this.setState({
index:data
})
});
}
render() {
return <div style={styles.outBox}>
<div>组件一</div><div>{"<"+this.state.index+">"}</div>
</div>
}
}
const styles = {
outBox:{
backgroundColor:"#fff",
width:"100%",
marginLeft:10,
display:"flex",
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding:'20px 0',
fontSize:20,
fontWeight:"bold",
}
}