首页 > 解决方案 > 具有不同变体的 Material-UI 排版

问题描述

如何使 Material-UI 的排版组件从其中的文本推断出变体?

我有以下代码:

import React from 'react';
import './styles.css';
import {createMuiTheme} from '@material-ui/core/styles';
import {ThemeProvider} from '@material-ui/styles';
import Typography from '@material-ui/core/Typography';

const theme = createMuiTheme({
    typography: {
        h1: {
            fontSize: 200,
        },
        h2: {
            fontSize: 5,
        },
    },
});

export default function App() {
    return (
        <ThemeProvider theme={theme}>
            <Typography>
                <h1>Text H1</h1>
                <h2>Text H2</h2>
            </Typography>
        </ThemeProvider>
    );
}

渲染时,“Text H1”的字体大小应为 200,“Text H2”的字体大小应为 5。不幸的是,事实并非如此。

只有当我将 Typography 的变体属性更改为 h1 或 h2 时,它才会更改字体大小。由于我有一个带有不同变体的长文本,我不想为每个变体创建一个 Typography 元素。

这是它的代码沙箱: https ://codesandbox.io/s/elegant-bouman-fz3j6?file=/src/App.js:0-604

标签: material-uitypography

解决方案


如果你想覆盖h1/h2你应该使用函数的overrides选项createMuiTheme

export const theme = createMuiTheme({
  overrides: {
    MuiTypography: {
      root: {
        "& h1": {
          color: "blue"
        },
        "& h2": {
          color: "red"
        }
      }
    }
  }
});

您可以在这里看到一个工作示例:https ://codesandbox.io/s/mui-theme-typography-override-styles-192jk?file=/demo.js


推荐阅读