gpt4 book ai didi

javascript - ReactJS 属性验证

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:28 26 4
gpt4 key购买 nike

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

最佳答案

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

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

所以:

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

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

关于javascript - ReactJS 属性验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50658339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com