首页 > 解决方案 > React MUI V5 AppBar背景颜色不变

问题描述

import React from "react";
import {
  AppBar,
  Toolbar,
  Grid,
  IconButton,
  InputBase,
  Badge,
} from "@mui/material";
import {
  ChatBubbleOutline,
  NotificationsNone,
  PowerSettingsNew,
} from "@mui/icons-material";
import { makeStyles } from "@mui/styles";

const useStyles = makeStyles({
  root: {
    backgroundColor: "#fff",
  },
});

const Header = () => {
  const classes = useStyles();
  return (
    <AppBar position="static" className={classes.root}>
      <Toolbar>
        <Grid container>
          <Grid item>
            <InputBase />
          </Grid>
          <Grid item sm>
            helo
          </Grid>
          <Grid item>
            <IconButton>
              <Badge badgeContent={4} color="secondary">
                <NotificationsNone />
              </Badge>
            </IconButton>
            <IconButton>
              <Badge badgeContent={3} color="primary">
                <ChatBubbleOutline />
              </Badge>
            </IconButton>
            <IconButton>
              <PowerSettingsNew />
            </IconButton>
          </Grid>
        </Grid>
      </Toolbar>
    </AppBar>
  );
};

export default Header;

我正在使用“makeStyles”进行样式设置,但它似乎无法更改 appbar 的背景颜色。应用栏是来自 v5(最新版本)的 mui 组件。我不知道为什么它没有改变。我是 MUI 的新手。有人请帮助我。

我可以使用内联“样式”及其以这种方式工作。但我需要使用 makeStyles 方法。

注意:我使用的是最新版本的 mui,但我不知道为什么它没有改变。

标签: reactjsmaterial-ui

解决方案


这是最新的 MUI v5。

问题是@mui/styles与React.StrictMode 或 React 18不兼容。 因此,我们需要将我们的根“App”组件包装在 index.js 文件中,并使用“StyledEngineProvider”并将 injectFirst 设置为 True。

import { StyledEngineProvider } from "@mui/material/styles";

ReactDOM.render(
  <StyledEngineProvider injectFirst>
    <App />
  </StyledEngineProvider>,

  document.getElementById("root")
);

然后它将起作用。


推荐阅读