React和Material UI的全局样式

16

我对React和Material UI还很陌生,但我必须编写一个具有良好样式的企业应用程序。我想使用某种全局样式来为我的应用程序提供支持(以便以后能够更改),并使用React中的功能组件(也许稍后我会添加redux)。

在React和Material(最新版本)中,全局样式的最佳实践方法是什么?

这个怎么样(ThemeProvider):https://material-ui.com/styles/advanced/? 我了解了MuiThemeProvider,但在Material版本4文档中找不到它。它已经过时了吗?MuiThemeProvider和ThemeProvider之间有什么区别?

React(客户端渲染)和Material UI(最新版本) 后端:Node


1
MuiThemeProvider在版本4中更名为ThemeProvider,但两个名称仍然有效 - Ryan Cogswell
5个回答

16
在 Material UI v5 中,您可以使用 GlobalStyles 来实现这一点。据我所知,GlobalStyles 只是 emotion 的 Global 组件的包装器。使用方法非常简单:
import GlobalStyles from "@mui/material/GlobalStyles";

<GlobalStyles
  styles={{
    h1: { color: "red" },
    h2: { color: "green" },
    body: { backgroundColor: "lightpink" }
  }}
/>

请注意,即使不将它放在 ThemeProvider 中,GlobalStyles 也会使用 defaultTheme(如果未提供)。
return (
  <>
    <GlobalStyles
      styles={(theme) => ({
        h1: { color: theme.palette.primary.main },
        h2: { color: "green" },
        body: { backgroundColor: "lightpink" }
      })}
    />
    <h1>This is a h1 element</h1>
    <h2>This is a h2 element</h2>
  </>
);

演示现场

Edit 58755118/global-styles-with-react-and-material-ui


“theme”参数的正确类型是什么?我正在使用您后面的TypeScript样式,但无法正确输入它。然而,使用“any”可以工作。 - basse
如何最好地实现 CSS 样式,例如 input[type='text']:focus {outline: none;}* {box-sizing: border-box;}*::before {box-sizing: border-box;}*::after {box-sizing: border-box;} - Fiddle Freak

14

你实际上可以使用Material UI编写全局样式:

const useStyles = makeStyles((theme) => ({
    '@global': {
        '.MuiPickersSlideTransition-transitionContainer.MuiPickersCalendarHeader-transitionContainer': {
            order: -1,
        },
        '.MuiTypography-root.MuiTypography-body1.MuiTypography-alignCenter': {
            fontWeight: 'bold',
        }
    }
}));

10

使用 Material UI 和 React 实现全局样式

// 1. GlobalStyles.js
import { createStyles, makeStyles } from '@material-ui/core';

const useStyles = makeStyles(() =>
  createStyles({
    '@global': {
      html: {
        '-webkit-font-smoothing': 'antialiased',
        '-moz-osx-font-smoothing': 'grayscale',
        height: '100%',
        width: '100%'
      },
      '*, *::before, *::after': {
        boxSizing: 'inherit'
      },
      body: {
        height: '100%',
        width: '100%'
      },
      '#root': {
        height: '100%',
        width: '100%'
      }
    }
  })
);

const GlobalStyles = () => {
  useStyles();

  return null;
};

export default GlobalStyles;

**然后在App.js中像下面这样使用它**

// 2. App.js
import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { Router } from 'react-router-dom';

import { NavBar, Routes, GlobalStyles, Routes } from '../';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: 'blue'
    }
  }
});

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <Router>
        <NavBar />
        <GlobalStyles />
        <Routes />
      </Router>
    </MuiThemeProvider>
  );
};

export default App;

这对我的React项目有效。


1
个人而言,我更喜欢将useStyles重命名为useGlobalStyles,然后直接在App组件中调用它。对我来说,GlobalStyles组件感觉像是一个不提供任何好处的间接层。两种方法都可以,只是个人偏好的选择。 - panepeter

6

对于全局样式,您可以像下面展示的那样使用它。 这是我使用过的最佳实现。

const theme = createMuiTheme({
  overrides: {
    MuiCssBaseline: {
      '@global': {
        html: {
          WebkitFontSmoothing: 'auto',
        },
      },
    },
  },
});

// ...
return (
  <ThemeProvider theme={theme}>
    <CssBaseline />
    {children}
  </ThemeProvider>
);

更多参考资料: 全局 CSS

3

根据我的经验,在使用 MuiThemeProvider 和 createMuiTheme 时都非常出色。然而,我正在使用 Material-UI 版本 3.9.2。

MuiThemeProvider 应该覆盖整个应用程序。在所有组件中,您只需要将样式对象传递给 withStyles 的函数改为传递一个传入主题的函数即可。

例:

import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import {NavBar, Routes} from '../'
const theme = createMuiTheme({
  palette: {
    primary: {
      main: 'red'
    },
  },
/* whatever else you want to add here */
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <NavBar />
        <Routes />
      </MuiThemeProvider>
    )
  }

然后在导航栏中,例如:

import React from 'react';
import { withStyles } from '@material-ui/core';
const styles = theme => ({
  root: {
    color: theme.palette.primary.main,,
  }
})

const NavBar = ({classes}) => {
  return <div className={classes.root}>navigation</div>
}

export default withStyles(styles)(NavBar);

希望能帮到你,对我来说非常有效!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接