【问题标题】:Default property value in React component with extended props using TypeScript 3使用 TypeScript 3 扩展道具的 React 组件中的默认属性值
【发布时间】:2019-06-30 06:38:31
【问题描述】:

我在 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 的编译错误,即使它应该是可选的,对吗?

是否应该做一些不同的事情来保持这些默认道具不是强制性的?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    Props 需要 className 属性。如果它是可选的,根据接口的使用方式,它应该在接口本身中标记为:

    interface Props extends WithNamespaces {
      className?: string;
    }
    

    或者使用它的地方:

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

    【讨论】:

    • 但正如我在问题中所述,我确实在 defaultProps 中将 className 初始化为 ''。
    • 对不起,我错过了评论。答案对你有用吗?
    猜你喜欢
    • 2016-09-13
    • 2020-03-14
    • 1970-01-01
    • 2019-12-27
    • 2021-01-26
    • 1970-01-01
    • 2020-12-21
    • 2020-01-25
    • 2018-04-12
    相关资源
    最近更新 更多