[英]Flow error for prop string in template literal
我有一個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
是一個字符串,而且,由於它不是必需的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;
根據此注釋 ,您的Props
類型可以被視為組件的“內部”類型。 如果您希望Props
成為組件API的文檔,則可以使用函數中的默認值:
type Props = {
placeholderText?: string,
};
const Textarea = (props: Props) => {
const { placeholderText = '' } = props;
return <textarea placeholder={`${placeholderText}`} />
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.