简体   繁体   English

TypeScript React 组件中的默认道具

[英]Default props in TypeScript React component

I recently found a way to set default props on React components, like this:我最近找到了一种在 React 组件上设置默认道具的方法,如下所示:

type Props = {
  children: any,
  color?: keyof typeof textColors,
};

const GTitle: React.FC<Props> = ({ children, color }) => (
  <Title color={textColors[color]}>
    {children}
  </Title>
);

GTitle.defaultProps = {
  color: 'primary',
};

The problem is that even if I define that there is a default property, the TypeScript keeps accusing the possibility of having an undefined value, as in the example below:问题是,即使我定义了一个默认属性,TypeScript 也会一直指责可能有一个未定义的值,如下例所示:

在此处输入图像描述

I managed to solve it using default arguments.我设法使用默认的 arguments 解决了这个问题。 TypeScript understands them just fine: TypeScript 很好理解它们:

type GTitleProps = {
  children: any,
  color?: keyof typeof textColors,
};

const GTitle: React.FC<GTitleProps> = ({
  children,
  color = 'primary',
}) => (
  <Title color={textColors[color]}>
    {children}
  </Title>
);

export default GTitle;

Addendum: defaultProps will be deprecated for function components.附录:function 组件将弃用defaultProps。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM