本文主要介紹在RN上運用ES6的繼承語法實現的一個業務場景,不涉及ES6繼承語法的介紹。
APP中會有一部分基礎按鈕,它們的樣式,用法,使用場景基本固定,這樣我們就可以做一個父按鈕,提供公共屬性和方法,然后子按鈕繼承父按鈕,子按鈕間只做樣式的區別,最后把子按鈕統一對外提供,這樣就做成一個公共按鈕組件,統一管理、使用我們所需的按鈕。
首先創建一個Buttons.js,這是外部引用的組件。然后在里面實現一個BaseButton的類,如下:
import React, {Component, PropTypes} from 'react';
import {View, Text, Image, TouchableOpacity, StyleSheet} from 'react-native';
const btnThemeColor = '#bc9956';
const btnDisableColor = '#cccccc';
class BaseButton extends Component {
constructor(props) {
super(props);
}
static propTypes = {
// 外邊框樣式
style: PropTypes.any,
// 按鈕的文字自定義樣式
textStyle: PropTypes.any,
// 按鈕是否可點
enable: PropTypes.bool,
// 按鈕文案
text: PropTypes.string,
// 這里只是舉例,可以根據需求繼續添加屬性...
};
static defaultProps = {
enable: true,
};
onBtnPress() {
if (!this.props.enable) return;
this.props.onPress && this.props.onPress();
}
}
接著在同一個文件寫要繼承BaseButton的子按鈕,比如:
/**
* 普通按鈕,沒有邊框,可通過style改變按鈕大小
*/
class NormalButton extends BaseButton {
render() {
const {style, enable, text, textStyle} = this.props;
return(
<TouchableOpacity
style={[styles.normalBtn, style, !enable && styles.disableBtn]}
activeOpacity={1}
onPress={()=>this.onBaseBtnPress()}
>
<Text style={[styles.btnTextWhite, textStyle]}>{text}</Text>
</TouchableOpacity>
);
}
}
該按鈕默認樣式如下:
const styles = StyleSheet.create({
normalBtn: {
height: 44,
borderRadius: 2,
backgroundColor: btnThemeColor,
alignItems: 'center',
justifyContent: 'center',
},
btnTextWhite: {
fontSize: fixedFontSize(16),
color: 'white',
},
disableBtnText: {
fontSize: fixedFontSize(16),
color: btnDisableColor,
}
});
最后導出該按鈕
export {NormalButton}
外部引用如下:
import {NormalButton} from '../../../components/ButtonSet';
render() {
return(
<NormalButton text='立即投資'/>
);
}
最終展示效果如下:
image.png
當然,你可以根據需求做更多的按鈕,統一管理和使用,使用者只需知道組件里有什么按鈕,并且能自由修改按鈕樣式,而不用每次寫重復的代碼。這是我的小小實踐,希望大神多多指點!