【问题标题】:Merge theme configuration settings in Material-UI在 Material-UI 中合并主题配置设置
【发布时间】:2020-01-21 10:24:01
【问题描述】:

我想设置cusom theme rules in Material-UI。我想制作明暗主题并使用一些常见设置扩展它们。

我认为将浅色和深色主题的通用设置放入一个单独的变量中,然后将它们合并在一起是个好主意。

但我遇到了用默认值覆盖自定义设置的问题。默认情况下,commonSettings 具有所有类型的设置,即使我没有定义它们。通过合并,默认设置会简单地覆盖自定义设置。所以,也许有人已经遇到过这种情况并且知道如何将两个设置数组合并为一个。

简单示例:

const commonSettings= createMuiTheme({
    breakpoints: {...},
    direction: 'ltr',
    typography: {...},
});

const lightThemeSettings = createMuiTheme({
    palette: {...},
});

const darkThemeSettings = createMuiTheme({
    palette: {...},
});

// Merge together
const lightTheme = { ...commonSettings, ...lightThemeSettings };
const darkTheme = { ...commonSettings, ...darkThemeSettings };

export default { lightTheme, darkTheme };

【问题讨论】:

  • 不要将createMuiTheme 用于commonSettings

标签: javascript arrays material-ui


【解决方案1】:

感谢Ryan Cogswell。他给了我正确的想法。

我找到了可行的解决方案。您应该在 createMuiTheme 对象中将 commonSettings 作为 arg 传递:

const commonSettings= {
    breakpoints: {...},
    direction: 'ltr',
    typography: {...},
};

const lightThemeSettings = createMuiTheme({
    palette: {...},
}, commonSettings // Merge together);

const darkThemeSettings = createMuiTheme({
    palette: {...},
}, commonSettings // Merge together);

export default { lightThemeSettings , darkThemeSettings };

【讨论】:

  • 对于任何人来说这可能会有所帮助 - 我对这种方法并不明显的是,您合并的设置 (commonSettings) 似乎没有获得第一个参数得到的自动调色板定义.这意味着如果您的 commonSettings 具有 primary: { main: '#ff0000' } 的调色板选项,则只有 main 颜色会合并到最终结果中。
【解决方案2】:

你的代码应该可以工作。

使用下面的代码并检查控制台,您将看到两个主题之间的区别。

import React from "react";
import ReactDOM from "react-dom";
import theme from "./themes";

console.log(theme.lightTheme.palette.primary);
console.log(theme.darkTheme.palette.primary);

function App() {
  return (
    <div>
      <h1>Check the console!</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

代码沙箱:https://codesandbox.io/s/dreamy-frost-xmw2j?fontsize=14&hidenavigation=1&theme=dark

【讨论】:

  • 感谢您的回答,但我认为您对问题的理解有误。在您的示例中,如果您更改 commonSettings 中的某些内容,则控制台中没有任何更改,因为所有属性都已被白色或深色设置覆盖。但我找到了可行的解决方案。请在下面检查我的答案。
猜你喜欢
  • 1970-01-01
  • 2020-09-01
  • 2021-04-08
  • 2020-02-21
  • 1970-01-01
  • 2018-02-15
  • 2023-03-12
  • 1970-01-01
  • 2022-08-09
相关资源
最近更新 更多