【问题标题】:How to type a React.ComponentType with a static property?如何使用静态属性键入 React.ComponentType?
【发布时间】:2018-03-07 05:05:15
【问题描述】:

我正在为 next.js 页面编写一个 HOC 组件,这个 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

【问题讨论】:

  • React 组件从来没有getInitialProps 方法。如果这些是特定组件,那么您必须输入 Component,而不是 React.Component。
  • @FelixKling 你的意思是创建一个类接口?
  • 我猜这会起作用。

标签: javascript reactjs flowtype nextjs


【解决方案1】:

这就是你要找的吗?

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

【讨论】:

  • 哦,是的,完全是我想要的!非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2012-11-30
  • 2010-10-01
  • 2014-02-12
相关资源
最近更新 更多