Flow 中的 PropTypes 组件检查等效项
PropTypes component checking equivalent in Flow
给出以下使用 PropTypes 的代码(参见 this 问题)
const SomeComponent = ({comp}) => {...}
SomeComponent.propTypes = {
comp: PropTypes.shape({
type: PropTypes.oneOf([SomeOtherComponent])
})
}
使用 Flow 类型的等效项是什么?
我只得到了:
const SomeComponent = ({comp}: {comp: React$Element<any>}) => {...}
使用 this 作为参考,但这将允许 comp
成为任何 React 组件。
如何对 prop 进行类型检查以确保它是使用 Flow 的特定 React 组件的实例?
简答:你不能。 React 元素是在 运行 时间创建的,Flow 只能使用通过自身静态分析得到的数据,其功能不够强大,无法确定将用于创建 React 的组件 class 运行 时间的元素。这很复杂,主要是因为用于创建元素的组件 class 只能在 运行 时定义。允许 Flow 尝试确定元素的 运行time 类型将不可避免地使其 运行 进入使用您想要的组件完全有效但 Flow 不允许的情况。
如果您想检查组件道具的类型,请在 运行 时间执行,如 this question 中所述。您可以通过使用指示 "development mode" 的全局变量来禁用这种生产检查。例如:
function elementIsOfType(element, typeName) {
if (!__DEV__) {
return true;
}
return element.type.displayName === typeName;
}
然后您可以将 __DEV__
变量设置为 false
以禁用所有 运行 时间检查。
从 Flow 0.53 开始,这可以使用 React.Element<typeof Component>
来完成。
给出以下使用 PropTypes 的代码(参见 this 问题)
const SomeComponent = ({comp}) => {...}
SomeComponent.propTypes = {
comp: PropTypes.shape({
type: PropTypes.oneOf([SomeOtherComponent])
})
}
使用 Flow 类型的等效项是什么?
我只得到了:
const SomeComponent = ({comp}: {comp: React$Element<any>}) => {...}
使用 this 作为参考,但这将允许 comp
成为任何 React 组件。
如何对 prop 进行类型检查以确保它是使用 Flow 的特定 React 组件的实例?
简答:你不能。 React 元素是在 运行 时间创建的,Flow 只能使用通过自身静态分析得到的数据,其功能不够强大,无法确定将用于创建 React 的组件 class 运行 时间的元素。这很复杂,主要是因为用于创建元素的组件 class 只能在 运行 时定义。允许 Flow 尝试确定元素的 运行time 类型将不可避免地使其 运行 进入使用您想要的组件完全有效但 Flow 不允许的情况。
如果您想检查组件道具的类型,请在 运行 时间执行,如 this question 中所述。您可以通过使用指示 "development mode" 的全局变量来禁用这种生产检查。例如:
function elementIsOfType(element, typeName) {
if (!__DEV__) {
return true;
}
return element.type.displayName === typeName;
}
然后您可以将 __DEV__
变量设置为 false
以禁用所有 运行 时间检查。
从 Flow 0.53 开始,这可以使用 React.Element<typeof Component>
来完成。