Material-ui不会根据主题更改版式颜色

时间:2020-04-30 10:10:56

标签: javascript reactjs material-ui

我正在尝试Material-ui,所以我创建了两个主题:

const darkTheme = createMuiTheme({
  palette: {
    type: "dark"
  }
});

const lightTheme = createMuiTheme({
  palette: {
    type: "light"
  }
});

但是当我使用Typography组件时,其color属性不会改变。更重要的是-颜色是从html继承而来的,因此Typography不了解当前主题。 是否可以在创建主题时配置印刷字体颜色或使用默认字体? 我试图像这样将color道具放在调色板对象中:

const darkTheme = createMuiTheme({
  palette: {
    type: "dark",
    typography: {
       body1: {
           color: '#fff'
       }
    }

  }
});

但是没有运气。我创建了codepen。而且我发现,如果将material-ui降级为3.1可以正常工作-.MuiTypography-body1类将设置与主题相对应的color属性。

1 个答案:

答案 0 :(得分:1)

Typography的默认行为是不对颜色进行任何处理。其原因是,通常,颜色是由与控制背景色相同的组件控制的。例如,如果将Typography元素放在Paper元素内,则Paper将同时控制background-colorcolor。为了使html和body元素符合您的主题,您需要使用CssBaseline

Typography提供了color道具,用于显式控制颜色。使用color="textPrimary"将与set the color of the Typography一样使用CssBaseline sets the color for the body element

下面是一个有效的示例,演示了此行为:

import React from "react";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
import Typography from "@material-ui/core/Typography";
import CssBaseline from "@material-ui/core/CssBaseline";
import Paper from "@material-ui/core/Paper";
import Button from "@material-ui/core/Button";

const darkTheme = createMuiTheme({
  palette: {
    type: "dark"
  }
});

const lightTheme = createMuiTheme({
  palette: {
    type: "light"
  }
});

export default function App() {
  const [topLevelDark, setTopLevelDark] = React.useState(false);
  return (
    <MuiThemeProvider theme={topLevelDark ? darkTheme : lightTheme}>
      <CssBaseline />
      <Button
        variant="contained"
        color="primary"
        onClick={() => {
          setTopLevelDark(!topLevelDark);
        }}
      >
        Toggle Themes
      </Button>
      <div>
        <Typography variant="body1">I'm within the top-level theme</Typography>
        <MuiThemeProvider theme={topLevelDark ? lightTheme : darkTheme}>
          <Paper>
            <Typography variant="body1">
              I'm in a Paper within the nested theme
            </Typography>
          </Paper>
          <Typography variant="body1" color="textPrimary">
            I'm in the nested theme with textPrimary color, but outside of a
            Paper. This makes me hard to read since nothing is setting the
            background-color to something contrasting.
          </Typography>
          <Typography variant="body1">
            I'm in the nested theme outside of a Paper with no explicit color.
          </Typography>
        </MuiThemeProvider>
      </div>
    </MuiThemeProvider>
  );
}

Edit material-ui-typography


有关使用多个主题的说明

在代码沙箱示例中,您有两个同级ThemeProvider元素,但是使用自己的自定义主题时,自定义主题必须位于顶层,这一点很重要。如果您对页面的一部分使用不同的主题,则应将其嵌套在顶级主题中。如果您有两个顶级ThemeProvider元素(即一个都不嵌套在另一个内),则它们都将尝试影响全局Material-UI CSS类名称。这意味着它们中只有一个会赢,而另一个似乎根本无法运作。当Material-UI检测到您位于嵌套ThemeProvider中时,它将在嵌套主题中使用不同的(后缀)类名称,并且嵌套主题将按预期工作。

相关答案: