1

我正在为 next.js 页面编写一个 HOC 组件,而这个 HOC 需要接受具有特定getInitialProps静态功能的组件。

我无法通过流程找出正确的打字方式:

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

演示

4

1 回答 1

4

这是你要找的吗?

// @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

(演示)

我自己觉得这很令人困惑。我从中改编了它:

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

于 2017-11-16T23:54:40.787 回答