[英]How to use Flow to enforce missing prop types
The flow definition 流程定义
declare type ReactComponent<Props> = Class<React$Component<void, Props, *>> | (props: Props) => React$Element<*>;
The Title Component 标题组件
/* @flow */
import React from 'react';
import Helmet from 'react-helmet';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import styles from './Title.css';
type Props = {
title: string,
subTitle?: string,
};
function Title({ title, subTitle }: Props) {
return (
<section>
<Helmet title={title} />
<h1>{title}</h1>
{subTitle && <h2>{subTitle}</h2>}
</section>
);
}
export default (withStyles(styles)(Title): ReactComponent<Props>);
So, now we have a Title Component that takes two props, both strings, with one of them being optional. 所以,现在我们有一个标题组件,它带有两个道具,两个字符串,其中一个是可选的。
I then try to use the above component in another component. 然后我尝试在另一个组件中使用上面的组件。
/* @flow */
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import styles from './TextureDetail.css';
import Title from '../../Title';
type Props = {
postData: Map<*, *>,
postTags: Array<*>,
};
function TextureDetail() {
return (
<div>
<Title />
</div>
);
}
export default (withStyles(styles)(TextureDetail): ReactComponent<Props>);
In this instance I expect flow to complain that I am using the component Title without the required props, but it does not do so. 在这种情况下,我希望流程抱怨我使用的组件标题没有所需的道具,但它没有这样做。 How do I configure flow that it actually checks for required types. 如何配置实际检查所需类型的流。
It's because the HOC (Higher Order Component) used to create Title
from isometric-style-loader
does not have associated flow types. 这是因为用于从isometric-style-loader
创建Title
的HOC(高阶组件)没有关联的流类型。 Flow automatically converts untyped libraries to any
, which is why you're not seeing any errors you'd normally expect to see from a component missing required props. Flow会自动将无类型库转换为any
类型,这就是为什么您没有看到通常期望从缺少必需道具的组件中看到的任何错误。
You can create bindings for its type using an example in the flow-typed
repository for a similarly structured HOC, such as react-css-modules . 您可以使用flow-typed
存储库中的示例flow-typed
结构化的HOC创建其类型的绑定,例如react-css-modules 。 You can also look around to see if someone else has released flow type definitions for this library, but I could not find any at the time of answering this question. 您还可以查看其他人是否已发布此库的流类型定义,但在回答此问题时我找不到任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.