react-native 发布/订阅事件总线EventBus 使用

前言

学过Android的同学应该都用过的一个框架->EventBus. 在我们需要的地方设置一个监听,在另外一段代码中,我们只要发送一个Event,则监听中的代码就会立即执行. 能很大程度上解耦代码.

我们都知道 react-native 是依赖于Node.js的,而在node.js 中,刚好有一个与EventBus 类似的机制 Events.

使用场景

在讲如何使用之前,我们先来看一下,Event 对我们有什么帮助,我们为什么需要使用它.

场景一

该页面显示的内容都是用户所订阅的主播,然后旁边与一个"已订阅"按钮,如果点击,则按钮变成"订阅",注意 头部 "我的订阅( counter )" 这里面的数字是会变动的.

常规处理可能是这样的,该页面肯定是包含多个 组件Component 组成,但 组件Component之间又没有直接关联,所以 我们只能用回调处理,一层层将事件发送到 顶级组件中,然后又分发出去.

使用 Events 后就简单多了,我们可以在头部Component 中注册监听,然后在 ListView的Item中发送Event事件即可实现需求.

场景二

用户登录前后页面状态的更改.

安装使用

安装

将命令行移动到项目的根目录,执行以下: npm install events --save

使用示例

  1. 新建CountEmitter.js 文件
'use strict';

const EventEmitter = require('events');

class CountEmitter extends EventEmitter{

}
const SingleCountEmitter = new CountEmitter();
export default SingleCountEmitter;

  1. 新建 TopPage.js 文件
'use strict';
import React from 'react';
import {
    View,
    Text
} from 'react-native';

import CounterEmitter from './CountEmitter';

class TopPage extends React.Component{

    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            count:0
        };
      }

    componentWillMount() {
        CounterEmitter.addListener('addCounter',()=>{
            let newCount=this.state.count+1;
            this.setState({
                count:newCount
            });
        });
        CounterEmitter.addListener('reduceCounter',()=>{
            let newCount=this.state.count-1;
            this.setState({
                count:newCount
            });
        });
    }

    render(){
        return (
            <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                <Text>Count: {this.state.count}</Text>
            </View>
        );
    }
}

export default TopPage;
  1. 新建BottomPage.js 文件
'use strict';
import React from 'react';
import {
    View,
    Text,
    TouchableOpacity
} from 'react-native';

import CounterEmitter from './CountEmitter';

class BottomPage extends React.Component{

    render(){
        return (
            <View style={{flex:1}}>
              <TouchableOpacity
                  onPress={()=>{
                  CounterEmitter.emit('addCounter');
              }}>
                  <View style={{width:100,height:100,borderRadius:10,backgroundColor:'red',justifyContent:'center',alignItems:'center'}}>
                      <Text style={{color:'white',fontSize:18}}>Add</Text>
                  </View>
              </TouchableOpacity>

              <TouchableOpacity
                  style={{marginTop:40}}
                    onPress={()=>{
                        CounterEmitter.emit('reduceCounter');
                    }}>
                    <View style={{width:100,height:100,borderRadius:10,backgroundColor:'green',justifyContent:'center',alignItems:'center'}}>
                        <Text style={{color:'white',fontSize:18}}>Reduce</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}

export default BottomPage;
  1. 修改index.android.js
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  View
} from 'react-native';

import TopPage from './TopPage';
import BottomPage from './BottomPage';


class AwesomeProject extends Component {
  
  render() {
    return (
      <View style={styles.container}>
        <TopPage/>
        <View style={{height:1,backgroundColor:'gray',width:500,marginBottom:50}} />
        <BottomPage/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

最终效果

效果: 在BottomPage 中点击 Add或Reduce 按钮能使 TopPage 的数字发生改变.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,916评论 25 708
  • 项目到了一定阶段会出现一种甜蜜的负担:业务的不断发展与人员的流动性越来越大,代码维护与测试回归流程越来越繁琐。这个...
    fdacc6a1e764阅读 3,209评论 0 6
  • 一、概述 EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handl...
    AiPuff阅读 1,293评论 2 0
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,072评论 0 29
  • 漫漫国庆长假,有些人在路上旅游观光,有些人在家追剧葛优躺,每个人都在过着自己喜欢的不喜欢的生活。有秀恩爱的...
    逆流的鱼dj阅读 375评论 0 1