美文网首页
react-native 继承语法的业务场景

react-native 继承语法的业务场景

作者: 朱man | 来源:发表于2017-10-10 00:35 被阅读259次

本文主要介绍在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

当然,你可以根据需求做更多的按钮,统一管理和使用,使用者只需知道组件里有什么按钮,并且能自由修改按钮样式,而不用每次写重复的代码。这是我的小小实践,希望大神多多指点!

相关文章

网友评论

      本文标题:react-native 继承语法的业务场景

      本文链接:https://www.haomeiwen.com/subject/tqymyxtx.html