【问题标题】:Exporting a custom theme from a UI library using Material-UI使用 Material-UI 从 UI 库中导出自定义主题
【发布时间】:2021-11-01 18:22:59
【问题描述】:

我正在为使用 Material-UI 的工作创建自定义 UI 库。 UI 库有一个自定义主题,我在其中添加了自定义公司颜色的调色板对象。主题存在于 UI 库中,对于存在于其中的元素,我可以在 makeStyles 中使用自定义颜色,但是当我尝试在主代码库中使用导出的主题时,自定义颜色会在 makeStyles 中引发错误。

我认为问题在于我没有导出主题的自定义模块。我不确定如何将其正确导出和导入到主代码库中。目前,我只是将主题文件导出并导入到主代码库中。

主代码库

import { theme } from 'customUILibrary';
...
<MuiThemeProvider theme={theme}>
    ...
</MuiThemeProvider>

CustomUILibrary

index.ts:

export { theme } from 'theme/theme';

主题/主题.ts

import {
    createTheme,
    responsiveFontSizes,
} from '@material-ui/core/styles';
import './extendPalette';

export const theme = responsiveFontSizes(createTheme({

    palette: {
        gradients: {
            primary: 'linear-gradient(270deg, #35C7E1 -10.76%, #1A92BD 121.8%)',
            secondary: 'linear-gradient(270deg, #194E94 0%, #317CA6 100%)',
        },
    },
 
}));

扩展调色板.ts

    declare module '@material-ui/core/styles/createPalette' {

    export interface PaletteOptions {
        gradients: {
            primary: string
            secondary: string,
        },
    }
    export interface Palette {
        gradients: {
            primary: string
            secondary: string,
        },
    }

}

自定义主题属性在 UI 库中与 UI 元素配合得很好,但是当导入主代码库时,自定义属性没有被拾取,实际上会导致错误。

【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    按照here 的建议,您可以这样做:

    declare module "@mui/material/styles" {
      interface Palette {
        custom: {
          pink: string;
        };
      }
      interface PaletteOptions {
        custom: {
          pink: string;
        };
      }
    }
    

    然后你可以安全地设置你在主题中的价值:

    
    const theme = createTheme({
      palette: {
        custom: {
          pink: "pink"
        }
      }
    });
    

    并在样式中使用它:

    <Button sx={{ color: "custom.pink" }}>Content</Button>
    

    见我的codesandbox example

    【讨论】:

    • 自定义主题属性在 UI 库中运行良好,但是当导入主代码库时,自定义属性没有被拾取,实际上会导致错误。
    • 您可能必须在使用库的地方执行declare module "@mui/material/styles",或者使用库包中的“.d.ts”文件可以完成这项工作。我无能为力,因为我无法访问您的代码文件结构。
    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 2019-02-06
    • 2021-11-14
    • 1970-01-01
    • 2020-12-20
    • 2020-01-28
    • 2019-07-15
    • 1970-01-01
    相关资源
    最近更新 更多