我正在从ReactJs转移到React-Native,并发现了这个函数结构in facebook's code for a react-native button
class Button extends React.Component<{
title: string,
onPress: () => any,
color?: ?string,
hasTVPreferredFocus?: ?boolean,
accessibilityLabel?: ?string,
disabled?: ?boolean,
testID?: ?string,
}> {
static propTypes = {
/**
* Text to display inside the button
*/
title: PropTypes.string.isRequired,
/**
* Text to display for blindness accessibility features
*/
accessibilityLabel: PropTypes.string,
/**
* Color of the text (iOS), or background color of the button (Android)
*/
color: ColorPropType,
/**
* If true, disable all interactions for this component.
*/
disabled: PropTypes.bool,
/**
* TV preferred focus (see documentation for the View component).
*/
hasTVPreferredFocus: PropTypes.bool,
/**
* Handler to be called when the user taps the button
*/
onPress: PropTypes.func.isRequired,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
};
...
}在ReactJS中,我使用propTypes检查来构建我的组件,所以:
a)在类定义(<{...}> )的括号内放入props规范的目的是什么?这在普通的ReactJS中也是可用的吗?
b)是否会检查传递的属性格式?如果是这样,为什么我在这里需要propTypes?
发布于 2018-06-02 23:30:03
为了清楚起见,括号内定义的适当术语称为泛型,它就像一个类型参数,当函数/类/任何东西不确定某物的类型时,因此它允许您填充空白-在本例中,是组件属性的类型。
特别是,这种语法看起来很像Flow,但TypeScript也是一种流行的类型检查选项。
所以:
propTypes用于在运行时检查类型,以便为不使用类型系统的人改进DX。通常,具有类型系统的项目只选择使用泛型来减少冗长,如果您使用的是类型系统,那么只有当您将组件发布给公众时,才真正需要propTypes。
发布于 2018-06-03 00:03:37
Facebook使用Flow (你可以在源代码上面看到注释)进行静态分析。您可以使用Typescript或任何其他分析器。定义props类型的主要目标是防止编程错误。阅读更多here
React组件需要2个通用的parameters React.Component<PropType, context> {}。
React.Component也有一些静态属性,比如
定义此组件可以take.
defaultProps的属性的propTypes定义了属性的默认值(如果这些属性不是从父级传递的)。关于你的问题:
将props规范放在类定义<{...}>的括号内的目的是什么?
为了定义组件可以采用的属性,用于静态分析和错误报告所需的属性,如果它们没有通过。
在普通的ReactJS中也可用吗?
是(您必须将Flow或TypeScript添加到项目中)
将检查传递的属性格式。如果是这样,为什么我这里需要propTypes??
是的,有些时候在编译时无法推断属性的类型,那么查看使用propTypes生成的任何警告将是很有用的。Credit
https://stackoverflow.com/questions/50658339
复制相似问题