如何用静态属性键入React.ComponentType?

时间:2017-09-26 05:38:09

标签: javascript reactjs flowtype nextjs

我正在为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

Demo

2 个答案:

答案 0 :(得分:3)

这是你正在寻找的吗?

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

答案 1 :(得分:1)

您甚至知道您正在寻找的确切术语。用如此多的先验知识谷歌搜索它是轻而易举的。只需在要转换为静态方法的方法前面使用关键字class SampleClass { static test() { console.log('I am a static method') } } SampleClass.test() // 'I am a static method'

{'items': {'---': '---', 
           ‘A’: ‘a’,
            ‘B’: ‘b’,
            ‘C: ‘c’, 
            ‘D’: ‘d’},
 'type1': 
      {
        "---":"---",
        "a1":"a1",
        "a2":"a2",
        "a3":"a3",
        "a4":"a4"
     },
  'type2': 
      {
        "---":"---",
        "b1":"b1",
        "b2":"b2",
        "b3":"b3",
        "b4":"b4"
     },

   'type3': 
      {
        "---":"---",
        "c1":"c1",
        "c2":"c2",
     },

    'type4': 
      {
        "---":"---",
        "d1":"d1",
        "d2":"d2",
        "d3":"d3"
     },
}

编辑:我的不好。我正在查看您的代码,而我正试图解释它。我很好奇。你有没有理由为React使用这种非传统的类/组件语法?除非您了解当前语法的细节,否则您可能会绊倒自己。如果您决定使用更传统的语法寻求帮助,我想我可以使用。