【问题标题】:Should I inherit react props from HTMLProps<HTMLElement>?我应该从 HTMLProps<HTMLElement> 继承反应道具吗?
【发布时间】:2019-09-09 17:08:07
【问题描述】:

我正在使用带有 TypeScript 的 React,并且我希望组件具有所有 HTML 属性。

interface MyComponentProps extends HTMLProps<HTMLElement> {

}

但是,有时我需要设置我的自定义道具类型,例如onClick

interface MyComponentProps extends HTMLProps<HTMLElement> {
    onClick?: (count: number) => void
}

但在 TypeScript 中,我无法更改子界面中已经存在的属性。有什么简单的解决办法吗?

我只是想到以下一种:

  • 定义我自己的父接口而不是HTMLProps(需要在每个文件中额外导入和许多自定义接口)
  • 重命名我的自定义道具(是的,但我想使用常见的道具名称,例如 onClickdata 而不是 onComponentClick_data

【问题讨论】:

    标签: javascript reactjs typescript inheritance react-props


    【解决方案1】:

    你可以试试这样的。首先,定义你的 props,然后从 HTMLProps 中省略它们,然后将你的 props 与之结合。

    interface OverrideProps {
      onClick?: (count: number) => void;
    }
    
    type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
    
    type MyComponentProps = Omit<
      React.HTMLProps<HTMLElement>,
      keyof OverrideProps
    > &
      OverrideProps;
    

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      相关资源
      最近更新 更多