想要在Material UI主题中动态更改(拾取)原色

时间:2018-09-18 04:48:50

标签: reactjs themes material-ui

有一个要求,我要授予用户访问权限,可以从诸如蓝色,橙色绿色的列表中选择其原色。我已将最新的Material UI用于前端。

现在,我可以将浅色主题更改为深色主题,但我的要求也是更改原色。请帮助我同样如何编码相同。

请检查所附屏幕:

enter image description here

1 个答案:

答案 0 :(得分:3)

import React from 'react';
import { render } from 'react-dom';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import Root from './Root';

import lightTheme from 'your-light-theme-path';
import darkTheme from 'your-dark-them-path';

const theme1 = createMuiTheme(lightTheme);
const theme2 = createMuiTheme(darkTheme)

class App extends React.Component {
  state = {
    isThemeLight: true;
  }
  onChange = () => {
    this.setState=({ isThemeLight: false })
  }
  render() {
     const { isThemeLight } = this.state;
     return (
       <MuiThemeProvider theme={isThemeLight ? theme1 : theme2}>
         <Root /> // your app here
         <button onClick={this.onChange}>Change Dark</button>
       </MuiThemeProvider>
     );
  }
}

render(<App />, document.querySelector('#app'));

您的lightThemedarkTheme可以是这样的文件

export default {
  direction: 'ltr',
  palette: {
    type: 'light',
     primary: {
       main: '#37b44e',
     },
     secondary: {
       main: '#000',
     },
  },
};

您可以在Material UI文档Theme Configuration中看到所有可配置的主题列表

方法2(用于主题更改运行时)

import React from 'react';
import { render } from 'react-dom';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import Root from './Root';

const theme1 = createMuiTheme(lightTheme);
const theme2 = createMuiTheme(darkTheme)

class App extends React.Component {
  state = {
    theme1: {
       palette: {
         type: 'light',
         primary: { main: '#37b44e' },
         secondary: { main: '#000' },
       },
    };
    theme2: {
       palette: {
         type: 'light',
         primary: { main: '#37b44e' },
         secondary: { main: '#000' },
       },
    };
    isThemeLight: true;
  }
  onChange = () => {
    this.setState=({ isThemeLight: false })
  }
  onChangeTheme1 = () => {
    this.setState(({theme1}) => ({
       theme1: { 
        ...theme1,
        primary: { main: 'red' },
       }
    }));
  }
  render() {
     const { theme1, theme2, isThemeLight } = this.state;
     return (
       <MuiThemeProvider 
         theme={isThemeLight ? createMuiTheme(theme1) : createMuiTheme(theme2)}
       >
         <Root /> // your app here
         <button onClick={this.onChange}>Change Dark</button>
         <button onClick={this.onChangeTheme1}>Change Palette Theme 1</button>
       </MuiThemeProvider>
     );
  }
}

render(<App />, document.querySelector('#app'));