所以,我读过 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。我对图书馆的使用方式感到困惑:
- Material-UI 的想法是我要用自定义 React 元素替换所有常规 html 标签吗?
- 有什么方法可以轻松地将主题排版中的样式应用到常规 html 标签(如 h1-6、p 等)?
- 我是否需要在某些顶级组件上使用 withStyles 自行设置所有常规 html 元素的样式?
最佳答案
- Is the idea of Material-UI that I'm going to replace all regular html tags with custom React elements?
没有。 Material UI(以及一般的 Material Design)中排版的想法是在您的应用程序主题中提供一致的变体比例:https://material.io/design/typography/the-type-system.html#
然后您可以以不同的方式使用此排版样式,如下面的 2. 和 3. 中所述
- Is there any way to apply the styles from the theme typography to regular html tags like h1-6, p, etc easily?
就像@Chimera.Zen 回答的那样,您可以使用withStyles
HOC 将主题样式和字体变体应用于任何反应组件或html 标签。但这是我发现更有用的另一种方法,通过在您的 JSS 样式中重用主题排版定义:
const styles = theme => ({
paragraph: {
...theme.typography.body1
}
});
const MyComponent = props => (
<p className={props.classes.paragraph}>
My styles text
</p>
);
- Am I expected to style all the regular html elements myself using withStyles on some top level component?
你不是。如果愿意,您可以为单个组件设置样式,但您可能更多地使用继承并使用容器组件(如 Paper、Drawer 等)或您自己的容器组件的默认样式。
您可以实现一个全局容器组件(例如“Root”或“App”...),将默认的“body1”样式应用到您的整个应用程序。
另一种方法是使用“jss-global”插件,如 MUI 作者此处所述https://github.com/mui-org/material-ui/issues/9988#issuecomment-426631645 :
import { withStyles } from '@material-ui/core/styles';
export default withStyles({
'@global': {
body: {
...theme.typography.body1
},
},
})(() => null);
关于javascript - 如何使用 Material-UI 将排版主题默认值应用于常规标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51862959/