流:当使用函数反应组件的默认道具时,“无法使用undefined [1]”访问计算属性

问题描述 投票:1回答:1
/* @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

我究竟做错了什么?

javascript reactjs react-native flowtype
1个回答
1
投票

看起来Flow与issues有一些defaultProps

您的问题的解决方案是将默认属性值作为默认参数传递:

const Button = ({ variant = 'primary' }: Props) => {
  return (
    <span style={{ color: colors.textColor[variant] }}>
      Foo
    </span>
  );
};

这是Flow editor的工作版本。

© www.soinside.com 2019 - 2024. All rights reserved.