Using createMuiTheme to override default styles on div's, p's, body

别来无恙 提交于 2019-11-28 10:27:14

问题


This is perhaps a simple Material UI Theme Customization question.

What I want to do is to override the default styling on <body> (and other common tags in the future). Right now at the root of my React tree:

import theme from './mui-theme'


ReactDOM.render(
  <Router>
    <ThemeProvider theme={theme}>
      <StylesProvider injectFirst>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <App />
      </StylesProvider>
    </ThemeProvider>
  </Router>,
  document.getElementById('root'),
);

There's a theme that specifies some things but leaves out 'body1'

const theme = useTheme() and console.log(theme) shows that it is defined as:

typography:
  body1:
    fontFamily: "Roboto,"Helvetica Neue""
    fontSize: "1rem"
    fontWeight: 400
    lineHeight: 1.5

This is the setting I want. However to use that setting I have to use the Typography tag with variant='body1'. Otherwise, text inside a div has styling provided by CssBaseline. That's the rule on the body tag: font-size: .875rem; which I wish to override.

Do people override styling provided by CssBaseline by using createMuiTheme? If so, I added:

body: {
    fontSize: '1rem',
  },

Which shows up on console.log(theme), but how tell the <body> tag to actually use that style?


回答1:


Here is an example of overriding this aspect of CssBaseline:

import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  "@global": {
    body: {
      ...theme.typography.body1
    }
  }
});

function MyCssBaseline() {
  return null;
}

MyCssBaseline.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(MyCssBaseline);

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import MyCssBaseline from "./MyCssBaseline";

function App() {
  return (
    <>
      <CssBaseline />
      <MyCssBaseline />
      <span>
        Here is some text in the body that is getting the body1 styling due to
        MyCssBaseline.
      </span>
    </>
  );
}
ReactDOM.render(<App />, document.querySelector("#root"));

Reference: https://material-ui.com/styles/advanced/#global-css



来源:https://stackoverflow.com/questions/56448538/using-createmuitheme-to-override-default-styles-on-divs-ps-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!