如何在带有Typescript的React中使用Material UI自定义主题 [英] How to use Material UI custom theme in React with Typescript

查看:104
本文介绍了如何在带有Typescript的React中使用Material UI自定义主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此工具 https://react-theming.github.io/create-mui-theme/我在上面提到的主题生成器页面的相应路径中获得了一个js文件和一个json文件,如上所述:

Using this tool https://react-theming.github.io/create-mui-theme/ I get a js file and a json file as mentioned on above theme generator page in respective paths as mentioned:

// src/ui/theme/index.js
/* src/ui/theme/theme.json */

现在,当我将文件扩展名留给js时,它们可以正常工作.一旦我尝试将js用作tsx文件,编辑器就会开始抱怨.我也通过tsconfig文件中的CRA Typescript完成了所有必要的设置.此页面上的其他必要配置 https://material-ui.com/guides/typescript/

Now they work fine when I leave the file extension to js. As soon as I try to use js as a tsx file the editor starts complaining. I have all the necessary setup done via CRA Typescript in tsconfig file also. Also necessary config from this page https://material-ui.com/guides/typescript/

当我尝试此操作不起作用时,是否有任何遗漏的主意?

When I try this it does not work, any ideas if I am missing something?

// My amended index.tsx file

import { createMuiTheme } from '@material-ui/core/styles';

const palette = {
  primary: { main: '#3f51b5' },
  secondary: { main: '#f50057' }
};
const themeName = 'San Marino Razzmatazz Sugar Gliders';

export default createMuiTheme({ palette, themeName });

此外,theme.json对我来说还是没有动过.我仍然在学习抱歉,如果这是接口问题以及如何使用它,您有什么想法吗?谢谢!

Also the theme.json is untouched by me. I am still learning sorry, any ideas if this is an interface problem and how to use it? Thanks!

推荐答案

材料UI已经定义了类型声明,因此您不能仅向其添加其他属性.您将必须通过模块扩充来扩展接口:

Material-UI has got typing declarations already defined so you can't just add extra properties to it. You would have to extend the interface via module augmentation:

import { createMuiTheme } from '@material-ui/core/styles';

declare module '@material-ui/core/styles/createMuiTheme' {
    interface ThemeOptions {    
        themeName?: string  // optional
    }
}

const palette = {
  primary: { main: '#3f51b5' },
  secondary: { main: '#f50057' }
};

const themeName = 'San Marino Razzmatazz Sugar Gliders';

export default createMuiTheme({ palette, themeName });

这篇关于如何在带有Typescript的React中使用Material UI自定义主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆