本文主要介紹在RN上運用ES6的繼承語法實現(xiàn)的一個業(yè)務場景庄撮,不涉及ES6繼承語法的介紹背捌。
APP中會有一部分基礎按鈕,它們的樣式洞斯,用法毡庆,使用場景基本固定,這樣我們就可以做一個父按鈕烙如,提供公共屬性和方法么抗,然后子按鈕繼承父按鈕,子按鈕間只做樣式的區(qū)別亚铁,最后把子按鈕統(tǒng)一對外提供蝇刀,這樣就做成一個公共按鈕組件,統(tǒng)一管理徘溢、使用我們所需的按鈕吞琐。
首先創(chuàng)建一個Buttons.js捆探,這是外部引用的組件。然后在里面實現(xiàn)一個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,
// 這里只是舉例黍图,可以根據(jù)需求繼續(xù)添加屬性...
};
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
當然奴烙,你可以根據(jù)需求做更多的按鈕助被,統(tǒng)一管理和使用,使用者只需知道組件里有什么按鈕切诀,并且能自由修改按鈕樣式揩环,而不用每次寫重復的代碼。這是我的小小實踐幅虑,希望大神多多指點丰滑!