【问题标题】:How to specify a unique React$Element as the flow type如何指定唯一的 React$Element 作为流类型
【发布时间】:2018-07-29 00:02:29
【问题描述】:

我试图指定一个函数应该只返回一个特定类型的 React$Element。查看源代码,以下应该可以工作,但不能:

/* @flow */

import React, { Component } from 'react';

type Props = {
  testID: string
}

class Price extends Component {
    props: Props;

    render() {
        return null
    }
}

function bla() : React$Element<Price> {
  return <Price testID="fds"/>;
}

我收到以下错误:

18:   return <Price testID="fds"/>;
             ^ props of React element `Price`. This type is incompatible with
17: function bla() : React$Element<Price> {
                                   ^ Price
18:   return <Price testID="fds"/>;
             ^ property `testID`. Property not found in
17: function bla() : React$Element<Price> {
                                   ^ Price

这是发生错误的游乐场链接:

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVBLAtgBzgJwBcwAlAUwEMBjQgGjAG8wBhOXOAOzI+IF8wo+NmADk+SjREBudIQCeOMmAAKQnAGcwAXkaowYQmXWEAkgBEAXGGP4MHAOape6KjArrNqjFSVkAHoYcACaarOxcPLr6+jhq6laqcBoyqACQ4sFk+AAUAJRR0elkhACu+BxgHCUwMHrRzs6oUCUcNBicYABGbnlgVuTUhAAkAKIwZFjchAA8Xj4AfAXipeVgs7Y+BkamZloARFAhe8DzMrxAA

(您可能需要将流版本从 v0.43.1 切换到 v0.43)

edit:正如 Nate 在下面建议的那样,我可以将 Props 作为类型参数传递,但是如果函数返回另一个具有相同 Props 类型的 React Element,flow 不会抱怨。

【问题讨论】:

  • 反对票有什么原因吗?
  • 我没有投反对票,但我的猜测是,在问题的原始版本中,您只是说它“不起作用”并且没有提供任何其他信息。此后,您进行了编辑以包含足够的信息。
  • 另外,我不知道如何解决您的实际问题,但React$Elements 的类型参数是针对道具的,而不是实际的元素类型。如果您将返回类型从 React$Element&lt;Price&gt; 更改为 React$Element&lt;Props&gt;,错误就会消失。

标签: reactjs flowtype


【解决方案1】:

Flow 0.53.0 包含对 React 的重大改进。其中一项更改是React.Element&lt;typeof Component&gt; type

要使用这种新类型,您必须使用 import * as React from 'react' 导入 React,这将导入 React 类型以及 React 库,因此您可以使用 React.Element。或者您可以显式导入您需要的类型,例如import React, { Component, type Element as ReactElement } from 'react',然后使用ReactElement

使用您的示例代码,它看起来像这样:

/* @flow */
import React, { Component, type Element as ReactElement } from 'react';

type Props = {
    testID: string
}

class Price extends Component<Props> {
    render() {
        return null
    }
}

function bla() : ReactElement<typeof Price> {
    return <Price testID="fds"/>;
}

或者,here it is in Flow's playground

【讨论】:

    【解决方案2】:

    1)还有一堆404是你用的默认版本0.43.1。您需要联系flow 来纠正问题

    2) 切换到上一个版本会发现以下问题:

    【讨论】:

    • 当然感谢我已经使用 0.43 的屏幕截图,应该添加我在问题中看到的错误。但是是的,有了这些错误,我仍然不明白我应该如何指定返回类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2019-10-14
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    相关资源
    最近更新 更多