英文:
How do I satisfy an "inexact function" error in Flow?
问题
以下是翻译好的部分:
我想在我的React组件中显示一个StatusImage
,如果组件的用户通过statusImage
属性提供了图像。否则,我只想保留图标所在位置的空白处。
它是有效的,但我得到了以下Flow错误,我无法解决。我正在使用flow-bin
版本0.113.0
无法将props.statusImage ? props.statusImage : (...) => <div />分配给StatusImage,因为不精确的函数[1]与精确的React.Element[2]不兼容。
[2] 121| const StatusImage: React$Element<*> =
[1] 122| props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);
我已经在Google上搜索了不精确的函数Flow错误,但无法找到任何解决我的问题的信息。这似乎是一个相对较新的错误,最近才开始在Flow中检查。
英文:
Ok so I've got a pretty straightforward scenario which works but my issue is keeping flow happy.
const StatusImage: React$Element<*> =
props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);
I want to display a StatusImage
within my React component if the user of the component supplies one through the statusImage
prop. Otherwise I just want to leave the space where the icon would be blank.
It works but I get the following flow error which I can't solve. I'm using flow-bin
version 0.113.0
Cannot assign props.statusImage ? props.statusImage : (...) => <div /> to StatusImage because inexact function [1] is
incompatible with exact React.Element [2].
[2] 121| const StatusImage: React$Element<*> =
[1] 122| props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);
I've google the inexact function flow error but can't find anything anywhere that solves my issue. This appears to be quite a new error which has only started to be checked for recently in flow.
答案1
得分: 1
I would recommend using the React.ComponentType<Props>
type if props.statusImage
can contain a stateless functional component or a class component. If props.statusImage
can only be a stateless functional component, then you could use React.StatelessFunctionalComponent<Props>
.
import * as React from "react";
type StatusImageComponent = React.ComponentType<{}>;
type Props = { statusImage?: StatusImageComponent };
function Foo(props: Props) {
const StatusImage =
props.statusImage === undefined ? () => <div /> : props.statusImage;
return (
<div>
<StatusImage />
</div>
);
}
英文:
I would recommend using the React.ComponentType<Props>
type if props.statusImage
can contain a stateless functional component or a class component. If props.statusImage
can only be a stateless functional component then you could use React.StatelessFunctionalComponent<Props>
.
import * as React from "react";
type StatusImageComponent = React.ComponentType<{}>;
type Props = { statusImage?: StatusImageComponent };
function Foo(props: Props) {
const StatusImage =
props.statusImage === undefined ? () => <div /> : props.statusImage;
return (
<div>
<StatusImage />
</div>
);
}
答案2
得分: 0
这似乎通过一些进一步的试验和错误来工作...
英文:
With some further trial and error this seems to work....
const StatusImage: React$Element<*> | () => React$Element<*> =
props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论