代码之家  ›  专栏  ›  技术社区  ›  CaribouCode

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

  •  3
  • CaribouCode  · 技术社区  · 6 年前

    我有一个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 是一个字符串,而且,由于它不是必需的属性,所以我将默认属性设置为空字符串,因此它从不为空或未定义。

    2 回复  |  直到 6 年前
        1
  •  2
  •   K.F    6 年前

    我不确定你是否退房了: 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;
    
        2
  •  1
  •   Tholle    6 年前

    根据 this comment ,您的 Props 类型可以看作组件的“内部”类型。如果你想的话 道具 为了记录组件的API,可以在函数中使用默认值:

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