【问题标题】:How to specify return type as a list of React components with Flow如何使用 Flow 将返回类型指定为 React 组件列表
【发布时间】:2018-11-11 13:07:48
【问题描述】:

我在其他地方看到有人使用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] 的静态与数组元素的类型参数ElementType [3] 中的NavbarItem [2] 不兼容。

[1] 类 [NavbarItem] 扩展组件

[2] getNavbarItems(): React$Element[]

[3] 声明类型 React$Element(来自 react.js)

上面的

[] 表示错误消息中 ^ 指向的位置。作为 flow 新手,我不确定这里的组件的静态是什么意思。

【问题讨论】:

  • 我刚刚在同样的情况下尝试了你的代码,它工作正常。可以添加NavbarItem 代码吗?
  • @KirillGlazunov 您具体需要看什么?整个课程有点长(读回来听起来像是重构的候选人哈)
  • 由于错误消息包含“NavbarItem 的静态”,我认为它可能是由某些静态方法或属性引起的。
  • @KirillGlazunov 查看编辑,我已经去掉了大部分的绒毛。
  • 它没有帮助(以及错误链接下隐藏的内容([1],[2],[3])?

标签: reactjs flowtype


【解决方案1】:

首先,您可能还应该使用React.Element&lt;typeof Component&gt; 类型而不是React$ElementType&lt;T&gt;,因为后者应该是内部的。 React.Element&lt;typeof Component&gt; 的文档还提示您需要使用 typeof operator 来指定您的意思是 type 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&lt;T&gt;,这仍然有效:

(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}
        />
      );
    });
  }
}

【讨论】:

  • 太棒了,很抱歉延迟接受。今天才回到办公室检查一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 2016-12-08
  • 2016-06-08
  • 2017-01-18
  • 2021-01-27
  • 2023-03-06
相关资源
最近更新 更多