【问题标题】:Using Flowtype with react-css-modules decorated components将 Flowtype 与 react-css-modules 装饰组件一起使用
【发布时间】:2017-02-11 01:00:00
【问题描述】:

下面是一个显示错误信息的简单组件:

// @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 没有产生任何结果。

我发现了什么:

【问题讨论】:

    标签: javascript reactjs flowtype react-css-modules


    【解决方案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 时保留类型信息,并允许流捕获预期的错误。

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 2017-04-10
      • 2016-10-11
      • 1970-01-01
      • 2020-05-01
      • 2017-10-10
      • 2020-02-03
      • 2018-11-15
      • 1970-01-01
      相关资源
      最近更新 更多