【问题标题】:How to write type annotation for higher-order component?如何为高阶组件编写类型注解?
【发布时间】:2017-09-13 21:53:33
【问题描述】:

我想为我的 react 15.6 项目写一个Higher-Order Component,但我不知道如何为它写类型注释。

我已经做了一些搜索

1。 The typeof type

喜欢typeof Component

2。函数类型

这对我来说似乎是正确的,因为类实际上是一个函数。但是函数的类型应该写成()=>Component<*>吗?在下面的代码中,any 的使用是否正确?它使类型“更广泛”。

 // @flow
    import React, {type Component} from 'react'

    const faded = (componentKlass:()=>{}) => class FadedWrapper
        extends React.Component<any> {
        //...
    }

3。看截图

这看起来不对,因为我们在这里需要一个类,但是警告让我想知道* 是什么(我还在上面的#2 中提出了它的可能用途。)?

警告说“应用多态类型需要。(可以使用* 来推断)”

我猜如果参数应该是Component 的某个子类的实例,流可以推断类型。

4。 from TypeScript

建议使用React.ComponentClass

【问题讨论】:

  • flow.org/en/docs/react/hoc 有帮助吗?
  • 谢谢!你真的很有帮助!我读完可以写一个答案,或者你可以写我打勾?
  • 文档中的 React.ComponentType 似乎丢失了。仍在搜索...
  • 请注意,Flow
  • 使用的流版本是0.53.1。我提出了issue 并得到了答案。我很快就会在这里写一个答案。

标签: javascript reactjs flowtype


【解决方案1】:

感谢@Paolo Moretti 在评论中指出the link,解决方案已经出现。

// @flow
import React from 'react';
import type { ComponentType } from 'react';
import { CSSTransitionGroup } from 'react-transition-group';
import './faded.css';

export const FirstChild = (props: any) => {
  const children = React.Children.toArray(props.children);
  return children[0] || null;
};

const faded = (ComponentKlass: ComponentType<*>) =>
  class extends React.Component<*> {
    render() {
      return (
        <CSSTransitionGroup
          transitionName="fade"
          transitionAppear={false}
          transitionAppearTimeout={1500}
          transitionEnter={true}
          transitionEnterTimeout={500}
          transitionLeaveTimeout={500}
          component={FirstChild}
        >
        {this.props.shouldRender ? 
          <ComponentKlass {...this.props} /> : null}
        </CSSTransitionGroup>
      );
    }
  };

export default faded;

应该注意ComponentType应该以这种方式导入:import type { ComponentType} from 'react',因为它不是React的属性('react'的默认导出)。我们不能像React.ComponentType 这样使用它,除非我们import * as React from 'react'

我使用componentKlass而不是ComponentKlass,似乎jsx/flow不介意我们是否使用大写的名称作为组件名称。当然通常不应该。但是它会在运行时引发错误,例如:

警告:Unknown props onCancel、city、shouldRender on tag。

onCancel & cities 用于我的装饰组件。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-25
    • 2017-09-26
    • 2017-10-12
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多