我有一个像这样运行 Flow 的 SFC React 组件:
// @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
是一个字符串,而且,由于它不是必需的 prop,我已将默认 prop 设置为空字符串,所以它永远不会为 null 或未定义。
最佳答案
我不确定您是否已结帐: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;
关于javascript - 模板文字中 Prop 字符串的流错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114669/