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

Coo*_*oop 5 javascript reactjs flowtype

我有一个 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;
Run Code Online (Sandbox Code Playgroud)

我从 Flow 中收到以下错误:

Cannot coerce 'props.placeholderText' to string because undefined[1] should not be coerced (References: [1])
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下这是怎么回事以及修复方法是什么吗?

据我所知,我已经明确告诉 Flow 是placeholderText一个字符串,而且,由于它不是必需的 prop,我已将默认 prop 设置为空字符串,因此它永远不会为 null 或未定义。

小智 5

我不确定您是否已结账: https: //github.com/facebook/flow/issues/1660

看来很多人都在讨论这个问题。不幸的是,我真的不认为任何建议的方法特别伟大。

第一个是 SFC 特定的,您可以这样做。

const Textarea = ({placeholderText = ""}: Props) => (
  <textarea placeholder={`${placeholderText}`} />
);
Run Code Online (Sandbox Code Playgroud)

^ 这里我们在从 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;
Run Code Online (Sandbox Code Playgroud)