【问题标题】:Checking React defaultProps with Flow使用 Flow 检查 React defaultProps
【发布时间】:2018-04-27 16:57:58
【问题描述】:

我一直在寻找将 Flow 添加到我的 React 项目中,但我不清楚如何键入检查 defaultProps。

假设我有一个非常基本的组件:

const React = require('react')

type MyComponentProps = {
  example: string
}

const MyComponent = (props: MyComponentProps) => <span>{props.example}</span>

MyComponent.defaultProps = {
  example: 1,
}

这里 example 属性的默认值是一个整数,即使我声明它应该是一个字符串,Flow 报告:No errors!

如果我添加以下内容:

let component = <MyComponent />

正如我所料,Flow 会抛出此错误:

13: let component = <MyComponent />
                     ^ props of React element `MyComponent`.
                       This type is incompatible with
7: const MyComponent = (props: MyComponentProps) => <span>{props.example}</span>
                                 ^ object type

Property `example` is incompatible:
10:   example: 1,
               ^ number. This type is incompatible with
4:   example: string
               ^ string

这是预期的行为吗?

我可以让 Flow 来检查 defaultProps 而不必调用组件本身吗?

【问题讨论】:

    标签: javascript reactjs types


    【解决方案1】:

    如果你使用 destructured props 语法设置默认 props,你会得到错误

    const React = require('react')
    
    type MyComponentProps = {
      example: string
    }
    
    const MyComponent = ({ example = 1}: MyComponentProps) => <span>{example}</span>
    

    这里是an example

    或者,您可以这样做:

    const React = require('react')
    
    type MyComponentProps = {
      example: string
    }
    
    const MyComponent = (props: MyComponentProps) => <span>{props.example}</span>
    
    const defaultProps: MyComponentProps = {
      example: 1,
    }
    
    MyComponent.defaultProps = defaultProps
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 2019-02-26
      • 2020-06-22
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多