/* @flow */
import React from 'react';
type Props = {
variant?: string,
}
const colors = {
textColor: {
disabled: '#868e96',
primary: '#ffffff',
}
};
const Button = (props: Props) => {
const { variant } = props;
return (
<span style={{ color: colors.textColor[variant] }}>
Foo
</span>
);
};
Button.defaultProps = {
variant: 'primary',
};
export default Button;
上面的代码导致以下流错误:
Cannot access computed property using undefined [1].
我还在Flow editor中添加了这个例子。
似乎Flow无法确定variant
变量的类型,因为将鼠标悬停在它上面会显示:
void | string
const variant: string
然而,这没有任何意义,因为variant
将是一个字符串(如果道具被传递),或者它将默认为'primary'
,这也是一个字符串。
我还检查了官方文档: Using Default Props for Functional Components
我究竟做错了什么?
看起来Flow与issues有一些defaultProps
。
您的问题的解决方案是将默认属性值作为默认参数传递:
const Button = ({ variant = 'primary' }: Props) => {
return (
<span style={{ color: colors.textColor[variant] }}>
Foo
</span>
);
};
这是Flow editor的工作版本。