【发布时间】: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
这是发生错误的游乐场链接:
(您可能需要将流版本从 v0.43.1 切换到 v0.43)
edit:正如 Nate 在下面建议的那样,我可以将 Props 作为类型参数传递,但是如果函数返回另一个具有相同 Props 类型的 React Element,flow 不会抱怨。
【问题讨论】:
-
反对票有什么原因吗?
-
我没有投反对票,但我的猜测是,在问题的原始版本中,您只是说它“不起作用”并且没有提供任何其他信息。此后,您进行了编辑以包含足够的信息。
-
另外,我不知道如何解决您的实际问题,但
React$Elements的类型参数是针对道具的,而不是实际的元素类型。如果您将返回类型从React$Element<Price>更改为React$Element<Props>,错误就会消失。