首页 > 解决方案 > 为了可读性,将 defaultProps 放在无状态组件定义之前

问题描述

为了可读性,有没有办法将contextTypesdefaultProps放在无状态的 React 组件之前?

type TopBarProps = {
    children: string,
    color: string
};

TopBar.defaultProps = {
    color: "white"
};

TopBar.contextTypes = {
    locale: PropTypes.string,
    colors: PropTypes.object,
    i18n: PropTypes.object,
    fontFamily: PropTypes.object,
    scale: PropTypes.number,
    alignStyle: PropTypes.string,
    navMethods: PropTypes.object,
    token: PropTypes.string,
    arrowName: PropTypes.string,
    materialArrows: PropTypes.object
};

export const TopBar = (props: TopBarProps, context) => {
    const { colors } = context;

    styles = styles || initStyles(context);

    return (
        <View style={styles.container}>
            <View>
                <Menu color={colors.colorFont} />
            </View>
            <View>
                <TopLabel color={props.color}>{props.children}</TopLabel>
            </View>
        </View>
    );
};

标签: reactjsreact-proptypes

解决方案


您可以先将它们定义为常量,然后在定义后将它们设置为组件的字段。由于它们的名称恰当,读者应该很清楚这些常量的用途。

const defaultProps = { ... }
const contextTypes = { ... }

export const TopBar = (props: TopBarProps, context) => { ... }

TopBar.defaultProps = defaultProps
TopBar.contextTypes = contextTypes

推荐阅读