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

btm*_*rex 7 html javascript css reactjs material-ui

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

const theme = createMuiTheme();

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <p>Hello world!</p>
    </MuiThemeProvider>
  );
};
Run Code Online (Sandbox Code Playgroud)

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

const theme = createMuiTheme();

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <Typography>Hello world!</Typography>
    </MuiThemeProvider>
  );
};
Run Code Online (Sandbox Code Playgroud)

它按预期工作.插入p标签以及排版css.我对如何使用库感到困惑:

  1. Material-UI的想法是我要用自定义的React元素替换所有常规的html标签吗?
  2. 有没有办法轻松地将主题排版中的样式应用到常规的html标签,如h1-6,p等?
  3. 我是否希望在某些顶级组件上使用withStyles自行设置所有常规html元素的样式?

Ric*_*tch 6

  1. 我要用自定义React元素替换所有常规html标签的Material-UI想法吗?

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

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

  1. 有什么方法可以轻松地将主题排版样式应用于常规html标签(例如h1-6,p等)吗?

就像@ 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>
);
Run Code Online (Sandbox Code Playgroud)
  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);
Run Code Online (Sandbox Code Playgroud)