【问题标题】:AppBar can not get theme with material-ui V5 (Bug or Change in v5????)AppBar 无法使用 material-ui V5 获取主题(V5 中的错误或更改????)
【发布时间】:2021-01-24 21:11:29
【问题描述】:

我尝试使用material-ui v5,但我发现AppBar 获取主题有问题,所以它没有显示任何颜色。

沙盒: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>
  );
}

在这个例子中:

  1. AppBar无法获取默认主题颜色,但Button可以获取默认主题颜色。
  2. 如果把material-ui改成v4就可以了。

你知道我的代码有什么问题吗?还是在 V5 中发生了一些变化?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    我从github上找到解决方案,简单的用&lt;StylesProvider injectFirst&gt;包裹代码,因为在material-ui v5中,Typography、Button等组件都迁移到了情感上,所以我们需要使用&lt;StylesProvider injectFirst&gt;来保留CSS在情感和JSS之间注入正确的顺序。

    这是来自@mnajdova 的原始答案 https://github.com/mui-org/material-ui/issues/24109#issuecomment-750794821

    以下代码应该可以正常工作

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

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2022-01-06
      • 2023-04-05
      • 2022-08-02
      • 2022-01-22
      • 2022-11-10
      • 2019-10-07
      • 1970-01-01
      相关资源
      最近更新 更多