【问题标题】:Flow error for prop string in template literal模板文字中道具字符串的流错误
【发布时间】:2018-12-09 09:53:40
【问题描述】:

我有一个 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 是一个字符串,此外,由于它不是必需的道具,我已将默认道具设置为空字符串,因此它永远不会为空或未定义。

【问题讨论】:

  • 这可能与设置 SFC defaultProps 的问题相同,也许可以试试看:stackoverflow.com/questions/40209352/…
  • @KF 感谢您的帮助,但我在该线程上没有取得任何进展,部分原因是它与 Typescript 有关,但我尝试的一些事情也没有帮助。

标签: javascript reactjs flowtype


【解决方案1】:

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

【讨论】:

  • 感谢您的建议。 Flow 无法正确处理这个简单的事情真是令人大开眼界。让我想知道 Typescript 是否会做得更好。
  • 你的第一个选项,虽然不是很理想,但通过设置({ placeholderText = defaultProps.placeholderText }: Props)
【解决方案2】:

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

type Props = {
  placeholderText?: string,
};

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

【讨论】:

  • 感谢您的帮助,但这种技术没有通过 Airbnb eslint 规则(prop 不是必需的,但没有相应的 defaultProp),也不是 React 文档指定如何应用默认值的方式。
  • @Coop 真不幸。你说得对,defaultProps 是设置默认 props 的更好方法,但目前似乎无法在类型中同时拥有可选 props 和 Flow 中的 defaultProps
  • 感谢您的帮助。我很震惊 Flow 无法处理这个,这似乎是一个基本要求。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 2020-02-16
  • 2023-03-19
  • 2016-06-08
  • 2016-10-28
相关资源
最近更新 更多