简体   繁体   English

更改自定义主题 Material-UI

[英]Change custom theme Material-UI

I am using Material-UI for a React project.我正在为 React 项目使用Material-UI However, I'm not sure as to how to apply a theme globally.但是,我不确定如何在全球范围内应用主题。

Here I have tried for individual components在这里,我尝试了单个组件

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CardCommon from '../../common/card/CardCommon';

import purple from '@material-ui/core/colors/purple';
import Button from '@material-ui/core/Button';

import { Link } from 'react-router-dom';
//const primary = red[500]; // #F44336
import { Paths } from '../../../Routes';

const theme = createMuiTheme({
    palette: {
        primary: { main: purple[500] }, // Purple and green play nicely together.
        secondary: { main: '#11cb5f' }, // This is just green.A700 as hex.
    },
});

So how can I change the primary and secondary colors globally?那么如何全局更改主要和次要颜色?

You can structure your app like this.你可以像这样构建你的应用程序。 Wrap the child components inside a MuiThemeProvider and pass a createMuiTheme object to it as a theme property value.将子组件包装在MuiThemeProvider ,并将createMuiTheme对象作为theme属性值传递给它。

Also typography: {useNextVariants: true } fixes the following error:还有typography: {useNextVariants: true }修复了以下错误:

( Warning: Material-UI: you are using the deprecated typography variants that will be removed in the next major release. ) Warning: Material-UI: you are using the deprecated typography variants that will be removed in the next major release.

The official Material UI docs have more detailed information on this:官方 Material UI 文档对此有更详细的信息:

Edit the index.js file as follows编辑 index.js 文件如下


    import React from 'react';
    import ReactDOM from 'react-dom'; 
    import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';  
    import './index.css';
    import App from './App';

    const theme = createMuiTheme({
       palette: {
          primary: {
             light: '#fff',
             main: 'rgb(23, 105, 170)',
             dark: '#000'
          },
          secondary: {
            main: '#f44336',
          },
       },
       typography: { 
          useNextVariants: true
       }
    });

    ReactDOM.render(
       <MuiThemeProvider theme = { theme }>
          <App />
       </MuiThemeProvider>, 
       document.getElementById('root')
    );

Material UI Version 5 code: Material UI 版本 5 代码:

import { ThemeProvider, createTheme } from '@mui/material/styles';

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

const theme = createTheme(themeOptions);

<ThemeProvider theme={theme}>
    <App />
</ThemeProvider>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM