【问题标题】:Accessing previous theme variables in createMuiTheme在 createMuiTheme 中访问以前的主题变量
【发布时间】:2023-03-15 19:17:01
【问题描述】:

运行 材质 UI 1.0.0-beta.24

我正在使用createMuiTheme 设置一个新主题:

import {createMuiTheme} from 'material-ui/styles';

const theme = createMuiTheme({
  typography: {
    fontSize: 16
  }
});

export default theme;

如何在此处直接访问我要覆盖的主题? 我想这样做,这是行不通的:

import {createMuiTheme} from 'material-ui/styles';

const theme = createMuiTheme({
  typography: {
    fontSize: theme.typography.fontSize + 2
  }
});

export default theme;

【问题讨论】:

    标签: reactjs material-ui theming jss


    【解决方案1】:

    您需要创建一个默认主题的实例并在定义自己的主题时使用它:

    import { createMuiTheme } from 'material-ui/styles';
    
    const defaultTheme = createMuiTheme();
    
    const theme = createMuiTheme({
      typography: {
        fontSize: defaultTheme.typography.fontSize + 2
      }
    });
    
    export default theme;
    

    【讨论】:

    • 这样做有没有任何与性能相关的问题?
    • 这行得通,但我最终得到了很多重复样式(不仅仅是覆盖,而是完全相同的声明)。也许这会在构建中清除(我只在开发过程中尝试过),但@zeckdude 的以下回答对我来说很好。
    【解决方案2】:

    您也可以创建您的主题,然后在创建theme 后添加到它。

    import { createMuiTheme } from 'material-ui/styles';
    
    const theme = createMuiTheme();
    theme.typography = {
      ...theme.typography,
      fontSize: theme.typography.fontSize + 2
    }
    
    export default theme;
    

    【讨论】:

    • 这个在不同的情况下是行不通的。例如,如果您使用 将主题作为主主题传递给其他组件,则默认属性将不再存在。您在覆盖排版时使用的示例,默认情况下附加到排版的一些属性不再存在,从而导致依赖于这些变量的组件出现错误。如果您只想使用一个默认主题,Ken 提供的上述解决方案更合适。
    • 你是对的。我已经更新了我的答案以保留所有默认的排版属性,并且只覆盖 fontSize 属性。感谢您的提醒。
    猜你喜欢
    • 2019-06-20
    • 2021-01-03
    • 2021-08-19
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多