材料-用户界面不会根据主题更改排版颜色

发布时间:2022-07-19 / 作者:清心寡欲
本文介绍了材料-用户界面不会根据主题更改排版颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在试用material-ui,所以我创建了两个主题:

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

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

但当我使用typography组件时,其颜色属性不会更改。更重要的是-颜色继承自html,因此Typography不知道当前主题。 有没有办法在创建主题或使用默认设置时配置排版颜色? 我曾尝试将color道具放在pallete对象中,如下所示:

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

  }
});

但运气不佳。我已经创建了codepen。在那里,我发现如果我将material-ui降级为3.1,它可以很好地工作--.MuiTypography-body1类设置与主题相对应的颜色属性。

推荐答案

的默认行为是不处理颜色。这样做的原因是,通常颜色由控制背景颜色的相同组件控制。例如,如果您将Typography元素放在Paper元素中,Paper将同时控制background-colorcolor。为了使html和Body元素支持您的主题,您需要使用CssBaseline

Typography提供color显式控制颜色的道具。使用color="textPrimary"将以与CssBaseline sets the color for the body element相同的方式set the color of the Typography。

下面是演示该行为的工作示例:

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 (
    
      
      
      
I'm within the top-level theme I'm in a Paper within the nested theme 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. I'm in the nested theme outside of a Paper with no explicit color.
); }


关于使用多个主题的说明

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

相关答案:

  • Change root background color with Material-UI theme

这篇关于材料-用户界面不会根据主题更改排版颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Material-ui does not change Typography color according to theme


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。