有時候在寫一些頁面的,如果把所有的業(yè)務(wù)邏輯和屬性寫到 Controler 里面碳竟,代碼太多余臃腫请毛,所以我們會用繼承,將一些通用的方法 寫到基類里面瞭亮,將通用屬性寫到基類里面方仿,那在React Native 里面,我們也可以這么寫;
優(yōu)點: 監(jiān)聽 和 常用屬性和基類方法放在基類實現(xiàn),子類實現(xiàn)業(yè)務(wù)邏輯和UI;
1. 自定義類繼承
創(chuàng)建 BasePage 基類 讓子類 SubClassPage 繼承基類;
BasePage 的實現(xiàn)
/* 定時密碼*/
class BasePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state={
title:'我是父類的屬性title',
subTitle:'我是父類的屬性subTitle',
};
}
componentWillMount() {
}
componentDidMount(){
}
componentWillUnmount() {
}
}
module.exports = BasePage;
SubClassPage的實現(xiàn)
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;
實現(xiàn)效果
2. 單例的實現(xiàn)
實現(xiàn)一個類似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;
在頁面調(diào)用
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());
實際打印結(jié)果這確實是個單例
娃哈哈
single1.title: 我是單例2
single2.title: 我是單例2
3. 發(fā)送通知 和接受通知
接收頁面
import {DeviceEventEmitter} from 'react-native';
componentDidMount(){
this.subscriptionListener = DeviceEventEmitter.addListener('notificationNameXXX', Function);
};
componentWillUnmount(){
this.subscriptionListener.remove();
};
發(fā)送頁面
import {DeviceEventEmitter} from 'react-native';
//調(diào)用事件通知
DeviceEventEmitter.emit('notificationNameXXX’,param);
注意
可以將通知的名稱此洲,定義成常量,放在某個配置文件內(nèi)委粉,這樣可以避免監(jiān)聽的名字錯導(dǎo)致的收不到通知消息