首页 > 解决方案 > 使用 TypeScript 3 扩展道具的 React 组件中的默认属性值

问题描述

我在 jsx 中使用对 defaultprops 的支持,如https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#support-for-defaultprops-in-jsx中所述

一切正常,除非我用另一个接口扩展道具。在这种情况下,我在子组件中扩展我的道具,例如

interface Props extends WithNamespaces { className: string; }

并声明默认道具:

const defaultProps = { className: '' };

*WithNamespaces是 react-i18next 的一个接口

在我的父组件中,我收到子组件缺少属性 className 的编译错误,即使它应该是可选的,对吗?

是否应该采取不同的措施来保持这些默认道具不是强制性的?

标签: reactjstypescript

解决方案


Props需要className道具。如果它是可选的,则取决于接口的使用方式,应在接口本身中将其标记为:

interface Props extends WithNamespaces {
  className?: string;
}

或者使用它的地方:

class Comp extends Component<Partial<Props>> {
  static defaultProps: Props = {
    className: ''
  }; 
  ...
}

推荐阅读