Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"));

Edit CssBaseline overrides

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...