使用TypeScript 3的带有扩展道具的React组件中的默认属性值

时间:2019-02-06 10:30:38

标签: reactjs typescript

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

一切正常,除非我 用其他界面扩展道具 。在这种情况下,我将道具扩展到

之类的子组件中

interface Props extends WithNamespaces { className: string; }

并声明默认道具:

const defaultProps = { className: '' };

* WithNamespaces 是react-i18next的接口

在我的父组件中,我得到了编译错误,即子组件缺少属性className,尽管它应该是可选的,对吧?

是否有其他方法可以使这些默认道具不是强制性的?

1 个答案:

答案 0 :(得分:1)

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

interface Props extends WithNamespaces {
  className?: string;
}

或使用它的地方:

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