如何使用Switch和withStyles()动态更改主题的调色板类型(深色/浅色)

时间:2019-12-15 20:48:21

标签: javascript reactjs typescript material-ui

我正在尝试创建一个更改站点暗模式的开关。它在某种程度上可以更改文本颜色。但是,即使使用CssBaseline,背景和其他所有内容都保持不变

这是重要的代码:

App.tsx

import blue from "@material-ui/core/colors/blue";
import createMuiTheme, {
  Theme,
  ThemeOptions
} from "@material-ui/core/styles/createMuiTheme";
import { PaletteOptions } from "@material-ui/core/styles/createPalette";
import { PaletteType } from "@material-ui/core";

const palette: PaletteOptions = {
  primary: {
    main: "#1976D2"
  },
  type: "light"
};

const defaultTheme = {
  palette: palette
};

export class ThemeManager {
  constructor(private theme: ThemeOptions) {
    this.useDarkMode(true);

    console.log(this.getTheme);
  }

  getThemePalette(): PaletteOptions | undefined {
    return this.theme.palette;
  }

  get getTheme() {
    return this.theme;
  }

  useDarkMode(dark: boolean) {
    const typeColor: PaletteType = dark ? "dark" : "light";

    const updatedTheme: ThemeOptions = {
      ...this.theme,
      palette: {
        ...this.theme.palette,
        type: typeColor
      }
    };

    this.theme = updatedTheme;
  }
}

const themeInstance = new ThemeManager(defaultTheme);

export default themeInstance;

theme.tsx

ReactDOM.render(
    < App />,
    document.getElementById('root')
);

index.js

{{1}}

打扰一下,听起来好像是我在问代码补给代码,但是老实说我很沮丧,因为我不知道如何处理withStyles()的样式信息

1 个答案:

答案 0 :(得分:0)

可以试试看 https://github.com/bluelovers/ws-react/tree/master/packages/material-ui-theme-state

import { useTheme, createTheme } from 'material-ui-theme-state/esm/global';

创建主题

let bool = prefersLightMode();
let theme: ThemeOptions | Theme;
    let setTheme: IThemeExtra["setTheme"];

    ([theme, setTheme] = useState({
        palette: {
            type: bool ? 'light': 'dark',
        },
        //direction: 'rtl'
    }));
const muiTheme = createTheme(theme, {
        setTheme,
    }).theme;

    return (<MuiThemeProvider theme={muiTheme}>{props.children}</MuiThemeProvider>)

其他任何想要更改的主题

const { theme, setTheme } = useTheme();

setTheme(theme => {

                theme.palette.type = (theme.palette.type !== 'light') ? 'light' : 'dark';

            return theme;
        }, true)

现场演示 https://tpl-next-app.now.sh/