代码之家  ›  专栏  ›  技术社区  ›  Simon Boudrias

如何键入反应。具有静态属性的ComponentType?

  •  1
  • Simon Boudrias  · 技术社区  · 7 年前

    我正在为next编写一个HOC组件。js页面,这个HOC需要接受具有特定 getInitialProps

    我无法使用flow找到正确的键入方式:

    const wrapComponent = (Component: React.ComponentType<*>) => {
        const original: Function = Component.getInitialProps;
    
        return class extends React.Component<*> {
            static async getInitialProps(ctx) {
                const props = await original(ctx);
                return {
                    ...props,
                    custom: 'a',
                };
            }
    
            render() {
                return <Component {...this.props} />;
            }
        }
    }
    

    我发现这个错误:

    5:     const original: Function = Component.getInitialProps;
                                                ^ property `getInitialProps`. Property not found in
    5:     const original: Function = Component.getInitialProps;
                                      ^ statics of React$Component
    

    Demo

    1 回复  |  直到 7 年前
        1
  •  4
  •   Harry Kao    7 年前

    这就是你要找的吗?

    // @flow
    
    import React from 'react';
    import type {ComponentType} from 'react';
    
    interface StaticInterface {
      fn(): void;
    }
    
    class NoStatic extends React.Component<{}> { 
    }
    
    class WithStatic extends React.Component<{}> {
      static fn() {}
    }
    
    const c1: ComponentType<{}> = NoStatic;                       
    const c2: ComponentType<{}> = WithStatic;                     
    const c3: ComponentType<{}> & StaticInterface = WithStatic;   
    // const c4: ComponentType<{}> & StaticInterface = NoStatic;     // NOT OK
    

    (demo)

    https://blog.bluematador.com/posts/enforcing-method-presence-in-react-components-with-flow

    相关:

    https://github.com/facebook/flow/issues/2048

    https://github.com/facebook/flow/pull/3994