如何将返回类型指定为具有Flow

时间:2018-06-01 11:38:54

标签: reactjs flowtype

我在其他地方看到人们使用React$Element<Type>所以我假设返回一个数组就像在最后添加[]一样简单。我在这里试过了:

navbarItems: INavbarItem[];

getNavbarItems(): React$Element<NavbarItem>[] {
  return this.navbarItems.map((navbarItem, index) => {
    return (
      <NavbarItem
        key={index}
        title={navbarItem.title}
        icon={navbarItem.icon}
        listPath={navbarItem.listPath}
        createPath={navbarItem.createPath}
      />
    );
  });
}

NavbarItem

class NavbarItem extends Component<Props, any> {
  constructor(props: Props) {
    super(props);
    /* stuff */
  }

  /* Couple of functions */

  render() {
    return (
      <li>
        <DropdownTitle/>
        {this.state.open && (
          <ul>
            <MenuItem>List</MenuItem>
            <MenuItem>Create</MenuItem>
          </ul>
        )}
      </li>
    );
  }
}

但是,当我运行流程时,我收到以下错误:

  

无法返回this.navbarItems.map(...),因为NavbarItem [1]的静态与数组元素的类型参数NavbarItem [3]中的ElementType [2]不兼容。

     

[1] class [NavbarItem]扩展Component

     

[2] getNavbarItems():React $ Element&lt; [NavbarItem]&gt; []

     

[3]声明类型React $ Element&lt; + [ElementType]:React $ ElementType&gt; (来自react.js)

上面的

[]表示^在错误消息中指向的位置。作为流动的新手,我不确定我的组件的静态意味着什么。

1 个答案:

答案 0 :(得分:1)

首先,你也应该使用React.Element<typeof Component>类型而不是React$ElementType<T>,因为后者应该是内部的。 React.Element<typeof Component>的文档还提示您需要使用typeof operator来指定NavbarItem类的类型

Try

import * as React from 'react'

// ...

class Foo {
   navbarItems: INavbarItem[];

  getNavbarItems(): React.Element<typeof NavbarItem>[] {
    return this.navbarItems.map((navbarItem, index) => {
      return (
        <NavbarItem
          key={index}
          title={navbarItem.title}
          icon={navbarItem.icon}
          listPath={navbarItem.listPath}
          createPath={navbarItem.createPath}
        />
      );
    });
  }
}

如果您使用React$ElementType<T>

,这仍然有效

Try

class Foo {
   navbarItems: INavbarItem[];

  getNavbarItems(): React$Element<typeof NavbarItem>[] {
    return this.navbarItems.map((navbarItem, index) => {
      return (
        <NavbarItem
          key={index}
          title={navbarItem.title}
          icon={navbarItem.icon}
          listPath={navbarItem.listPath}
          createPath={navbarItem.createPath}
        />
      );
    });
  }
}