为了可读性,将 defaultProps 放在无状态组件定义之前
Putting the defaultProps before a stateless component definition for the sake of readability
有没有办法,为了可读性,将 contextTypes 和 defaultProps 放在无状态 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>
);
};
使用 function
语法定义组件,如下所示:
export function 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>
);
};
由于名为 hoisting
的东西,它应该可以工作
您可以先将它们定义为常量,然后在定义后将它们设置为组件的字段。由于它们的命名很恰当,reader 常量的用途应该很明显。
const defaultProps = { ... }
const contextTypes = { ... }
export const TopBar = (props: TopBarProps, context) => { ... }
TopBar.defaultProps = defaultProps
TopBar.contextTypes = contextTypes
有没有办法,为了可读性,将 contextTypes 和 defaultProps 放在无状态 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>
);
};
使用 function
语法定义组件,如下所示:
export function 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>
);
};
由于名为 hoisting
的东西,它应该可以工作您可以先将它们定义为常量,然后在定义后将它们设置为组件的字段。由于它们的命名很恰当,reader 常量的用途应该很明显。
const defaultProps = { ... }
const contextTypes = { ... }
export const TopBar = (props: TopBarProps, context) => { ... }
TopBar.defaultProps = defaultProps
TopBar.contextTypes = contextTypes