如何使用 Material-UI 将排版主题默认应用于常规标签?

IT技术 javascript html css reactjs material-ui
2021-05-07 10:36:31

所以,我已经阅读了https://material-ui.com/style/typography/并且我正在加载 Roboto 字体。我希望有一个简单的组件,如:

const theme = createMuiTheme();

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <p>Hello world!</p>
    </MuiThemeProvider>
  );
};

将使用 Roboto(默认字体)设置 p 标签的样式。但这不会发生。如果我将代码更改为:

const theme = createMuiTheme();

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <Typography>Hello world!</Typography>
    </MuiThemeProvider>
  );
};

它按预期工作。插入了 p 标签以及排版 css。我对图书馆的使用方式感到困惑:

  1. Material-UI 的想法是我要用自定义 React 元素替换所有常规 html 标签吗?
  2. 有什么方法可以轻松地将主题排版中的样式应用到 h1-6、p 等常规 html 标签中吗?
  3. 我是否希望自己在某个顶级组件上使用 withStyles 来设置所有常规 html 元素的样式?
2个回答
  1. Material-UI 的想法是我要用自定义 React 元素替换所有常规 html 标签吗?

不。Material UI(以及一般的 Material Design)中的排版思想是为您的应用程序主题提供一致的变体比例:https : //material.io/design/typography/the-type-system.html#

然后,您可以以不同的方式使用这种排版样式,如下面的 2. 和 3. 中所述

  1. 有什么方法可以轻松地将主题排版中的样式应用到 h1-6、p 等常规 html 标签中吗?

就像@Chimera.Zen 回答的那样,您可以使用withStylesHOC将主题样式和字体变体应用于任何react组件或 html 标签但这是另一种方法,我觉得它更有用,通过在您的 JSS 样式中重用主题排版定义:

const styles = theme => ({
  paragraph: {
    ...theme.typography.body1
  }
});

const MyComponent = props => (
  <p className={props.classes.paragraph}>
    My styles text
  </p>
);
  1. 我是否希望自己在某个顶级组件上使用 withStyles 来设置所有常规 html 元素的样式?

你不是。如果您愿意,您可以设置单个组件的样式,但您可能会更多地使用继承并使用容器组件(如 Paper、Drawer 等)或您自己的容器组件的默认样式。

您可以实现一个全局容器组件(例如“Root”或“App”...),将默认的“body1”样式应用于整个应用程序。

另一种方法是使用 MUI 作者https://github.com/mui-org/material-ui/issues/9988#issuecomment-426631645在这里解释的“jss-global”插件

import { withStyles } from '@material-ui/core/styles';

export default withStyles({
  '@global': {
    body: {
      ...theme.typography.body1
    },
  },
})(() => null);
  1. 是的,但您不必这样做。

  2. 是的,使用withStyles组件styles并被定义。请参阅答案末尾的示例

  3. Paper、Drawer 等组件将采用主题默认值,也可以在启动<MuiThemeProvider>. 普通的 HTML 元素需要在使用它的组件中定义一个样式,或者在样式表中定义一个类名。

如果你有发言权style.root,你可以应用到材料的UI组件,divspanpa,等,如果它应用到MUI组件,在风格style.root将覆盖默认值。

使用Material-UI Paper组件作为示例和styles.paragraph附加示例:

const styles = theme => ({
  root: {
    ...theme.mixins.gutters(),
    paddingTop: theme.spacing.unit * 2,
    paddingBottom: theme.spacing.unit * 2,
  },
  paragraph: {
    color: '#FFF',
    textAlign: 'center',
    paddingTop: theme.spacing.unit * 2,
    paddingBottom: theme.spacing.unit * 2,
});

这些样式现在可以应用于任何元素

<div className={styles.root}>
  <Paper className={styles.root}>
    <Typography component="p" className={styles.paragraph}>
      Paper can be used to build surface or other elements for your application.
    </Typography>
  </Paper>
</div>