Javascript 如何在React with Typescript中使用材质UI自定义主题

Javascript 如何在React with Typescript中使用材质UI自定义主题,javascript,reactjs,typescript,material-ui,create-react-app,Javascript,Reactjs,Typescript,Material Ui,Create React App,使用此工具 我在上述主题生成器页面中分别获得了一个js文件和一个json文件,路径如下所述: // src/ui/theme/index.js /* src/ui/theme/theme.json */ 现在,当我将文件扩展名留给js时,它们工作得很好。当我尝试使用js作为tsx文件时,编辑器开始抱怨。我已经通过Tconfig文件中的CRA Typescript完成了所有必要的设置。也需要从本页进行配置 当我尝试这个方法时,它不起作用,如果我遗漏了什么,有什么想法吗 // My amended

使用此工具 我在上述主题生成器页面中分别获得了一个js文件和一个json文件,路径如下所述:

// src/ui/theme/index.js
/* src/ui/theme/theme.json */
现在,当我将文件扩展名留给js时,它们工作得很好。当我尝试使用js作为tsx文件时,编辑器开始抱怨。我已经通过Tconfig文件中的CRA Typescript完成了所有必要的设置。也需要从本页进行配置

当我尝试这个方法时,它不起作用,如果我遗漏了什么,有什么想法吗

// 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。 我仍在学习抱歉,如果这是一个界面问题,有什么想法以及如何使用它吗?
谢谢

材质UI已经定义了类型声明,所以您不能只向其添加额外的属性。您必须通过模块扩充来扩展接口:

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 });

@kaspero编写的内容,但却使其更通用,因为键入样式是一种非常有效的方法:

// imported theme from separate file
import { themeDetails } from './utils/theme';

declare module '@material-ui/core/styles/createMuiTheme' {
        interface ThemeOptions {
          [key: string]: any; // 
        }
    }
const theme = createMuiTheme({ themeDetails, 'theme name' });

谢谢你的快速回复。它工作得很好。我不知道这一点,因为我在TS的MUI文档中找不到自定义主题的示例。有很多示例使用这种语法,但我不会在我的解决方案中实现这些示例。谢谢你!不客气!如果你认为它能解决问题,你能将其标记为已接受吗:)同时,你也能从中学到大量的TS是的,我有,但上面说:(感谢您的反馈!声誉低于15的人所投的票会被记录,但不会更改公开显示的帖子分数。我描述了一个类似的解决方案,但我也使用const断言为自定义属性提供文字类型: