【问题标题】:Flowtype, React and defaultPropsFlowtype、React 和 defaultProps
【发布时间】:2018-09-10 22:12:13
【问题描述】:

经过数小时的搜索和测试,我没有成功找到任何解决方案来让 flow 理解 defaultProps

Try Flow example

使用这个模型是不一致的:

type PropsType = {|
  size?: 'small' | 'big',
|};


class Letter extends PureComponent<PropsType> {

  static defaultProps = {
    size: 'small',
  }

}

谢谢

编辑

在 Tomasz Mularczyk 的建议下,我创建了another Try Flow example

type PropsType = {|
  size: 'small' | 'big',
|};

而不是

type PropsType = {|
  size?: 'small' | 'big',
|};

但是

defaultProp size 不再输入:

static defaultProps = {
  size: 'BAD DEFAULT PROPS', // no error (?!)
}

解决方案

查看 Tomasz Mularczyk 的回答

+

不要等待当前组件上的流错误(在我的情况下),而是在哪里导入和声明它。(似乎是半静态的?)

【问题讨论】:

    标签: reactjs react-native flowtype


    【解决方案1】:

    只需从size 类型中删除?。 Flow 将自动看到您创建了defaultProps,并且不需要它。

    来自docs:

    要键入默认道具,请将静态 defaultProps 属性添加到您的 类。

    ...

    React 还支持无状态功能组件上的默认道具。 与类组件类似,无状态功能的默认道具 组件无需任何额外的类型注释即可工作。

    【讨论】:

    • 如果我从 size PropsType 中删除 ?static defaultProps 将变得无用,这将生成运行时 proptypes 警告,因为 size 不会被传递
    • @MadeInMoon Flow 能够“看到”您已为所需道具声明默认属性。并且在您使用该组件时不需要它。
    • 感谢您的宝贵时间。请参阅上面的编辑以及其他 Try Flow 示例
    • 找到了解决方案:删除 ? from size PropsType + 并且不要等待当前组件中的错误,而是何时导入和声明!
    • @MadeInMoon 感谢分享,我不会考虑 :)
    猜你喜欢
    • 2016-08-15
    • 2019-02-26
    • 2019-06-03
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2017-02-19
    • 2018-04-27
    • 1970-01-01
    相关资源
    最近更新 更多