我在这上面砸头撞墙。我正在尝试将flowtype合并到一些React项目中。在大多数情况下,键入似乎效果很好。但是,我使用的库(react-jss)使用HOC将样式表类注入(inject)到您的组件中。问题在于该模块没有流类型,因此由于我的所有组件都被此HOC包装,因此它破坏了我的组件上的所有props验证。

我已经能够基于我看到的一些github isuse添加一些类型,所以至少我知道我是从react-jss HOC中获得一个组件,但是从flow的 Angular 来看,这个新组件没有与之相关的 Prop 。 View ,因此我不会因未能提供所需的 Prop 或类型错误的 Prop 而出错(消除了流程带来的很多好处)。这是我复制粘贴以获得基本的react-jss HOC定义的内容:

declare type FunctionComponent<A> = (props: A) => ?React$Element<any>;

declare type ClassComponent<D, A, S> = Class<React$Component<D, A, S>>;

declare type Component<A> = FunctionComponent<A> | ClassComponent<any, A, any>;

declare type Fn1<A, B> = (a: A) => B;

declare type HOC<A, B> = Fn1<Component<A>, Component<B>>;

declare module 'react-jss' {
  declare module.exports: (styleSheet: Object) => HOC<A, B>;
}

请记住,react-jss默认导出(injectStyles)的rought签名是这样的:
function injectStyles(styleSheet: AnObject)(Component: ReactComponent<Props>): ReactComponent<PropsWithStyleClasses>

最佳答案

您可以尝试以下定义:

declare module 'react-jss' {
  // Export these
  declare type FunctionComponent<P> = (props: P) => ?React$Element<any>;
  declare type ClassComponent<D, P, S> = Class<React$Component<D, P, S>>;

  declare type Klasses<CSS> = {
    [classname: $Keys<CSS>]: string,
  };

  declare type JSSProps<CSS> = {
    classes: Klasses<CSS>,
    sheet: {
      attached: boolean,
      classes: Klasses<CSS>,
      deployed: boolean,
      linked: boolean,
      options: Object,
      renderer: mixed,
      rules: mixed,
    },
  };

  declare type Injector = {
    <Props, State, DefaultProps, CSS>(component: ClassComponent<DefaultProps, Props, State>): ClassComponent<DefaultProps, $Diff<Props, JSSProps<CSS>>, void>;
    <Props, CSS>(component: FunctionComponent<Props>): FunctionComponent<$Diff<Props, JSSProps<CSS>>>;
  };

  declare function exports<Props, State, DefaultProps, CSS>(
    CSS: CSS,
  ): Injector
}

请注意,导入注入(inject)的组件时,流程存在一些问题。使用类时,一切正常:
// Test.js
class Test extends React.Component<void, { text: string }, void> {
    ...
}
export const StyledTest = injectSheet(style)(Test)

// Main.js
...
render() {
    return <StyledTest /> // ERROR here, missing `text` prop
}

但是对于功能组件,您需要显式键入:
// Test.js
const Test = (props: { text: string }) => {
    ...
}
export const StyledTest: FunctionComponent<{ text: string }> = injectSheet(style)(Test) // Explicitly type this

// Main.js
...
render() {
     return <StyledTest /> // ERROR here, so it works!
}

我不确定这些问题是否已解决,但是此设置对我来说效果很好。

关于javascript - 流类型高阶组件(HOC) Prop 类型保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42728045/

10-12 12:35
查看更多