【问题标题】:Material UI v4: extending PaletteColorOptionsMaterial UI v4:扩展 PaletteColorOptions
【发布时间】:2021-10-10 11:38:33
【问题描述】:

我想在 Material UI v4 (v4.11) 的调色板中做一些非常简单的事情:向PaletteColorOptions 添加一个新字段。假设我要添加darker?: string

这是相关 Material UI 模块中的类型定义:

createPalette.d.ts

export type PaletteColorOptions = SimplePaletteColorOptions | ColorPartial;

export interface SimplePaletteColorOptions {
  light?: string;
  main: string;
  dark?: string;
  contrastText?: string;
}

a merged PR to Material UI 在他们的文档中添加了一个示例,说明如何通过模块扩充添加新的调色板颜色选项。这是他们的建议:

declare module '@material-ui/core/styles/createMuiTheme' {
  interface PaletteColor {
    darker?: string
  }
  interface SimplePaletteColorOptions {
    darker?: string
  }
}

我试过这个,但它似乎不起作用 - 尝试将 darker 添加到其中一个颜色对象时出现以下错误 - 表明我没有设法将新字段添加到 PaletteColorOptions

类型 '{ 黑暗:字符串;主要:字符串;对比文本:字符串;较暗:字符串; }' 不可分配给类型 'PaletteColorOptions |不明确的'。 对象字面量只能指定已知属性,并且“PaletteColorOptions”类型中不存在“深色”.ts(2322) createPalette.d.ts(105, 3):预期类型来自属性“primary”,该属性在此处在“PaletteOptions”类型上声明

我还尝试将类似的定义添加到 createPalette 模块(再次通过上面示例中建议的模块扩充),但我得到了与上面相同的 TypeScript 错误。

declare module '@material-ui/core/styles/createPalette' {
  interface PaletteColor {
    darker?: string
  }
  interface PaletteColorOptions {
    darker?: string
  }
}

任何指导将不胜感激。

【问题讨论】:

    标签: typescript material-ui


    【解决方案1】:

    我最终设法解决了它。这是我的做法:

    palette.ts(我们创建的用于定义调色板的文件)

    interface ExtendedPaletteColorOptions extends SimplePaletteColorOptions {
      darker?: string
    }
    
    interface ExtendedPaletteOptions extends PaletteOptions {
      primary: ExtendedPaletteColorOptions
      secondary: ExtendedPaletteColorOptions
      text: Partial<TypeText>
      error: ExtendedPaletteColorOptions
      warning: ExtendedPaletteColorOptions
      info: ExtendedPaletteColorOptions
      success: ExtendedPaletteColorOptions
      // And your custom palette options if you defined them, e.g:
      // brand: ExtendedPaletteColorOptions
    }
    
    const palette: ExtendedPaletteOptions = {
      // Our palette, which now supports the new `lighter`, for example:
      primary: {
        main: '#555555',
        dark: '#333333',
        darker: '#111111',
      }
    }
    

    theme.d.ts(我们为 material-ui 模块的模块扩充创建的文件)

    declare module '@material-ui/core/styles/createPalette' {
      interface PaletteColor {
        lighter: string
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-14
      • 2019-10-14
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 2020-12-11
      相关资源
      最近更新 更多