ReactJS属性验证

Men*_*des 5 javascript reactjs react-native

我正在从ReactJs转到React-Native,并在facebook的代码中找到了一个反应原生按钮的这个函数结构:

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,
  };

  ...
}
Run Code Online (Sandbox Code Playgroud)

在ReactJS中,我只使用check来构建我的组件propTypes,所以:

a)在类定义(<{...}>)的括号内使用props规范的目的是什么?在普通的ReactJS中是否也可以使用它?

b)是否会检查传递的属性格式?如果是这样,为什么我在这里需要propTypes?

kin*_*aro 4

为了清楚起见,括号内定义的正确术语称为泛型,它就像一个类型参数,当函数/类/任何东西不确定某物的类型是什么时,它可以让你填补空白 - 在在本例中,是组件的 props 的类型。

特别是,这种语法看起来像Flow,但TypeScript也是类型检查的流行选项。

所以:

  • 泛型用于在编译时使用组件进行类型检查。这是类型检查器特有的语法,在普通 JS 中不可用。
  • propTypes用于在运行时检查类型,以提高不使用类型系统的人的 DX。

一般来说,具有类型系统的项目只选择使用泛型来减少冗长,如果您使用类型系统,propTypes则只有在向公众发布组件时才真正需要。