模板文字中道具字符串的流错误

Flow error for prop string in template literal

我有一个带有 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 设置为空字符串,所以它永远不会为空或未定义。

根据this comment,您的Props类型可以看作是组件的"internal"类型。如果您希望 Props 成为组件 API 的文档,您可以在函数中使用默认值:

type Props = {
  placeholderText?: string,
};

const Textarea = (props: Props) => {
  const { placeholderText = '' } = props;
  return <textarea placeholder={`${placeholderText}`} />
};

我不确定您是否已结帐: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;