繁体   English   中英

模板文字中prop字符串的流错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM