【问题标题】:How do I set a global font colour in React which uses Material UI如何在使用 Material UI 的 React 中设置全局字体颜色
【发布时间】:2021-03-07 06:42:42
【问题描述】:

我有一个使用 Material UI 构建的 React 应用程序。我创建了自己的主题覆盖(请参阅下面的摘录),但字体的颜色需要为紫色 #391960,而不是 rgba(0, 0, 0, 0.87)。如何覆盖整个网站的默认字体颜色?

这是我的主题的摘录

import { createMuiTheme } from "@material-ui/core";

const theme = createMuiTheme({
  palette: {
     text: {
         light: "#ffffff",
          main: "#391960",
          dark: "#140b1d",
    },
});

export default theme;

我希望在我的 theme.js 文件中添加上述内容会导致所有字体颜色更改为 #391960,因为我没有对组件中的字体应用任何样式。例如:

import theme from "./styles/theme";

<ThemeProvider theme={theme}>
        <Typography variant="h1" component="h1">
          Page Title
        </Typography>
</ThemeProvider>

但是,上述 Typography 组件中的文本仍然是深灰色。我成功地使用以下代码更改了此排版组件的大小,因此这证明我将主题正确地拉入组件中:

  typography: {
    h1: {
      fontSize: "2rem",
      fontWeight: 700,
    },

如果我不能使用 theme.js 文件设置站点范围的颜色,我在想我可以有一个全局样式表,它以某种方式从主题中提取正确的颜色?例如(我知道这行不通!)

body {
 color: theme.palette.main
}

任何帮助将不胜感激!

谢谢,

凯蒂

【问题讨论】:

    标签: css reactjs material-ui styles jsx


    【解决方案1】:

    有两件事无法让您的主题得到有效应用。

    1. official docs 为参考,这些是palette.text 对象的当前默认属性
    const theme = createMuiTheme({
      palette: {
        text: {
          primary: 'rgba(0, 0, 0, 0.87)',
          secondary: 'rgba(0, 0, 0, 0.54)',
          disabled: 'rgba(0, 0, 0, 0.38)',
          hint: 'rgba(0, 0, 0, 0.38)',
        },
      },
    });
    

    如果您想设置不同的全局原色,那么您的 theme.js 文件应如下所示:

    import { createMuiTheme } from '@material-ui/core/styles';
    
    const theme = createMuiTheme({
      palette: {
        text: {
          primary: '#391960',
        },
      },
    });
    
    export default theme;
    

    请注意,如果您也想覆盖其他属性(辅助、禁用、提示),您还可以设置不同的颜色。

    1. 要正确显示 MUI 主题和组件,您需要 CSS Baseline component

    Material-UI 提供了一个 CssBaseline 组件,用于启动一个优雅、一致且简单的基线以供构建。

    import React from "react";
    import { ThemeProvider, CssBaseline, Typography } from "@material-ui/core";
    import theme from "./theme";
    
    export default function App() {
      return (
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <Typography variant="h1" component="h1">
            Page Title
          </Typography>
        </ThemeProvider>
      );
    }
    

    这里是一个功能性的CodeSandbox reproduction,希望对你有帮助。

    【讨论】:

    • 太棒了!!!非常感谢开尔文 - 这非常有效。我非常感谢您非常明确的答复。我已经为此苦苦挣扎了太久,而您为我节省了很多时间。再次感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多