Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - AppBar can not get theme with material-ui V5 (Bug or Change in v5????)

I try to use material-ui v5, but I found the AppBar has a problem to get theme, so it doesn't show any color.

sandbox: https://codesandbox.io/s/material-uiappbar-roquc?file=/src/App.tsx:111-403

export default function App() {
  return (
    <div className="App">
      <AppBar color="primary" position="static">
        <Toolbar>I am AppBar! Where is my color?</Toolbar>
      </AppBar>

      <Button color="primary" variant="contained">
        color
      </Button>
    </div>
  );
}

In this example:

  1. The AppBar can not get default theme color, but the Button can get the default theme color.
  2. If you change the material-ui to v4, then it is all right.

Do you know, what's wrong in my code? Or there is something changed in V5?

question from:https://stackoverflow.com/questions/65876021/appbar-can-not-get-theme-with-material-ui-v5-bug-or-change-in-v5

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

1 Answer

0 votes
by (71.8m points)

I found solution from github, simply wrap the code with <StylesProvider injectFirst>, because in material-ui v5, the Typography, Button, etc components are migrated to emotion, so we need to use the <StylesProvider injectFirst> to keep the CSS injection right order between emotion and JSS.

Here is the original answer from @mnajdova https://github.com/mui-org/material-ui/issues/24109#issuecomment-750794821

The following code should work correctly

import { Button, AppBar, Toolbar, StylesProvider } from "@material-ui/core";
import React from "react";

export default function App() {
  return (
    <StylesProvider injectFirst>
      <div className="App">
        <AppBar color="primary" position="static">
          <Toolbar>I am AppBar! Where is my color?</Toolbar>
        </AppBar>

        <Button color="primary" variant="contained">
          color
        </Button>
      </div>
    </StylesProvider>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...