React Native(8) 自定义继承、单例实现、通知

有时候在写一些页面的,如果把所有的业务逻辑和属性写到 Controler 里面,代码太多余臃肿,所以我们会用继承,将一些通用的方法 写到基类里面,将通用属性写到基类里面,那在React Native 里面,我们也可以这么写;

优点: 监听 和 常用属性和基类方法放在基类实现,子类实现业务逻辑和UI;

1. 自定义类继承

创建 BasePage 基类 让子类 SubClassPage 继承基类;

BasePage 的实现

/* 定时密码*/
class BasePage extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state={
      title:'我是父类的属性title',
      subTitle:'我是父类的属性subTitle',
    };
  }

  componentWillMount() {
  }

  componentDidMount(){
  }

  componentWillUnmount() {
  }   
}


module.exports = BasePage;

SubClassPage的实现

class SubClassPage extends BasePage{
  constructor(props, context) {
    super(props, context);
    this.state={
      ...this.state,
      newTitle:'子类的State 属性',
    };
  }

  render(){
    return (
      <View style={styles.containerAll}>
         <View style={styles.contentView}>
          <Text>{this.state.title}</Text>
          <Text>{this.state.subTitle }</Text>
          <Text>{this.state.newTitle }</Text>
         </View>
      </View>
      );
  }
  
  componentWillMount() {
  }

  componentDidMount(){
  }

  componentWillUnmount() {
  }   

}

module.exports = BasePage;

实现效果


2. 单例的实现

实现一个类似ios 单例写法的对象 SingleManager;

'use strict';
var React = require('react-native');

let instance = null;

class SingleManager extends React.Component {
  constructor(props, context) {
    super(props,context);

    if(!instance){
      instance = this;
    }
    this.state={
      title:null,
      subTitle:null,
    };
    return instance;
  }

  setTitle(title){
    this.state.title = title;
  }

  getTitle(){
    return this.state.title;
  }
}

module.exports = SingleManager;

在页面调用

var single1 = new SingleManager();
single1.setTitle('娃哈哈');
console.log(single1.getTitle());


var single2 = new SingleManager();

single2.setTitle('我是单例2')
console.log('single1.title:   '+single1.getTitle());
console.log('single2.title:   '+single2.getTitle());

实际打印结果这确实是个单例

娃哈哈
single1.title:   我是单例2
single2.title:   我是单例2

3. 发送通知 和接受通知

接收页面

import  {DeviceEventEmitter} from 'react-native';

componentDidMount(){
    this.subscriptionListener = DeviceEventEmitter.addListener('notificationNameXXX', Function);
};

componentWillUnmount(){
    this.subscriptionListener.remove();
};

发送页面

import  {DeviceEventEmitter} from 'react-native';

//调用事件通知
DeviceEventEmitter.emit('notificationNameXXX’,param);

注意
可以将通知的名称,定义成常量,放在某个配置文件内,这样可以避免监听的名字错导致的收不到通知消息

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

推荐阅读更多精彩内容