【问题标题】:How to properly use typescript module augmentation for material-ui components?如何为 material-ui 组件正确使用 typescript 模块扩充?
【发布时间】:2018-09-05 14:54:36
【问题描述】:

我已经阅读了现有的答案herehere,但它们似乎已经过时了。

我尝试了以下方法来增加按钮组件的类型定义,无论是在单独的类型文件 (.d.ts) 中还是在反应组件本身中,但都无济于事。

declare module "@material-ui/core/Button" {
  export interface ButtonProps {
    to?: string;  
  }
}

当放入单独的 .d.ts 文件时,我得到一个“JSX 元素类型 'Button' 没有任何构造或调用签名。”错误。

如果与组件本身放在同一个文件中,编译器只会抱怨类型 'IntrinsicAttributes & ButtonProps & { children?: ReactNode; 上不存在属性 'to' }' 就好像什么都没有定义一样。

所以我想知道当前在 material-ui (v3.0.2) 中增加组件类型定义的正确方法。

谢谢你,干杯

【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    ButtonProps 接口实际上是在@material-ui/core/Button/Button 模块中声明的。您的组件文件中的以下代码应该可以工作:

    declare module "@material-ui/core/Button/Button" {
      export interface ButtonProps {
        to?: string;  
      }
    }
    

    【讨论】:

    • 如何命名/定位文件在哪里放置这段代码?
    • 你应该可以直接把它放到一个react组件文件或者一个单独的.d.ts文件中,先导入增强的接口,即import { ButtonProps } from "@material-ui/core/Button"
    • 由于某种原因它不适用于Link :) 显然这是另一个原因 - Subsequent property declarations must have the same type. 所以感谢您的快速回答:)
    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 2021-08-10
    • 2022-11-22
    • 2020-07-22
    • 1970-01-01
    • 2020-02-01
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多