pubsub-js无关组件之间的信息传输

我们在使用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",
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值