使用Flowtype和react-css-modules装饰组件

时间:2016-10-03 06:23:05

标签: javascript reactjs flowtype react-css-modules

以下是显示错误消息的简单组件:

// @flow
import styles from 'styles/components/Error';
import React from 'react';
import CSSModules from 'react-css-modules';

type Props = {
  message: string
}

const Error = ({ message }: Props) => {
  return (
    <div styleName="error">
      {message}
    </div>
  );
};

export default CSSModules(Error, styles);

请注意,它需要message属性。现在如果我在某个地方使用这个组件:

<Error />;

Flowtype应警告我Error缺少必需的属性message,但事实并非如此。如果我没有用react-css-modules包装我的Error组件,Flowtype会按预期工作。

我认为我需要为Flowtype声明一个类型,以便了解包装的组件,但我的Google-fu没有产生任何结果。

我做了什么:

1 个答案:

答案 0 :(得分:1)

最近在GitHub上讨论过这个问题。以下是相关问题:https://github.com/facebook/flow/issues/2536

简而言之,问题是Flow没有CSSModules函数的任何类型信息,因此返回类型被推断为any

换句话说:

export default Error; // the type of this export is (_: P) => ?React$element<any>
export default CSSModules(Error, styles); // the type of this export is any

长话短说,您可以提供自己的类型定义。我将在此处粘贴@gcanti在原始问题中建议的那个:

declare module 'react-css-modules' {

  declare type CssOptions = {
    allowMultiple?: boolean,
    errorWhenNotFound?: boolean,
  };

  declare type FunctionComponent<P> = (props: P) => ?React$Element<any>;
  declare type ClassComponent<D, P, S> = Class<React$Component<D, P, S>>;

  declare function exports<D, P, S, C: ClassComponent<D, P, S> | FunctionComponent<P>>(reactClass: C, styles: Object, cssOptions?: CssOptions): C;
}

将上述内容保存在decls/react-css-modules.js或类似内容中,然后将.flowconfig配置为:

[libs]
decls/.js

这会在将组件包装到CSSModules时保留类型信息,并允许流程捕获预期的错误。