0
点赞
收藏
分享

微信扫一扫

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

笙烛 2022-03-12 阅读 66

安装插件:

用法

发送消息(发布方可传给多个订阅方)

//作为发布方 把消息发送到名为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",
    }
}

举报

相关推荐

0 条评论