我一直在寻找将Flow添加到我的React项目中,但我不清楚如何键入check defaultProps。
我们说我有一个非常基本的组成部分:
const React = require('react')
type MyComponentProps = {
example: string
}
const MyComponent = (props: MyComponentProps) => <span>{props.example}</span>
MyComponent.defaultProps = {
example: 1,
}
此处示例道具的默认值是一个整数,即使我声明它应该是一个字符串,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而不必调用组件本身吗?
答案 0 :(得分:0)
如果您使用分解后的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