【问题标题】:ReactJS properties validationReactJS 属性验证
【发布时间】:2023-03-25 17:03:02
【问题描述】:

我正在从 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?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    为了清楚起见,括号内定义的专有术语称为泛型,当函数/类/不确定某物的类型时,它就像一个类型参数,所以它可以让你填写空白 - 在这种情况下,组件道具的类型。

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

    所以:

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

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

    【讨论】:

      【解决方案2】:

      Facebook 使用Flow(您可以在源代码顶部查看 cmets)进行静态分析。您可以使用 Typescript 或任何其他分析器。定义props 类型的主要目的是防止编程错误。阅读更多here

      React 组件需要 2 个泛型 parameters React.Component&lt;PropType, context&gt; {}

      1. 道具类型
      2. 上下文

      React.Component 也有一些静态属性,比如

      1. propTypes 定义了该组件可以采用的道具。
      2. defaultProps 定义 props 的默认值(如果它们不是从父级传递的)。

      回答你的问题:

      在里面有 props 规范的目的是什么 类定义中的括号 ?

      定义组件可以采用的props,用于静态分析和错误报告所需的props,如果它们没有通过。

      这在普通的 ReactJS 中也可用吗?

      是的(您必须将 Flow 或 TypeScript 添加到您的项目中)

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

      是的,有时在编译时无法推断道具的类型,那么查看使用propTypes 生成的任何警告会很有用。 Credit

      【讨论】:

        猜你喜欢
        • 2011-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多