我有一个SFC React组件,其中Flow的运行方式如下:
// @flow
import React from 'react';
type Props = {
placeholderText?: string,
};
const defaultProps = {
placeholderText: '',
};
const Textarea = (props: Props) => (
<textarea placeholder={`${props.placeholderText}`} />
);
Textarea.defaultProps = defaultProps;
export default Textarea;
我从Flow中收到以下错误:
Cannot coerce 'props.placeholderText' to string because undefined[1] should not be coerced (References: [1])
有人可以解释这是什么意思,以及解决方法是什么吗?
据我所知,我已经明确地告诉Flow placeholderText
是一个字符串,此外,由于它不是必需的道具,因此我将默认道具设置为空字符串,因此它是永远不会为null或未定义。
答案 0 :(得分:2)
我不确定您是否已结帐:https://github.com/facebook/flow/issues/1660
似乎很多人都在谈论这个问题。不幸的是,我真的不认为任何建议的方法都特别出色。
第一个是SFC特定的,您可以改成这样。
const Textarea = ({placeholderText = ""}: Props) => (
<textarea placeholder={`${placeholderText}`} />
);
^这里我们设置默认值,因为我们从props解构了placeholderText。它将适合您的示例,但对于其他更复杂的情况,则不是理想的选择。
另一个选项也不理想:从placeholderText中删除可选类型以有效地解决错误:
import React from 'react';
type Props = {
placeholderText: string, // here's the change
};
const defaultProps = {
placeholderText: '',
};
const Textarea = (props: Props) => (
<textarea placeholder={`${props.placeholderText}`} />
);
Textarea.defaultProps = defaultProps;
export default Textarea;
答案 1 :(得分:1)
根据this comment,您的mylifeisdone
类型可以看作是组件的“内部”类型。如果您希望Props
作为组件API的文档,则可以在函数中使用默认值:
Props