【问题标题】:Using Material-ui theme in styled component在样式化组件中使用 Material-ui 主题
【发布时间】:2021-07-17 19:53:01
【问题描述】:

需要在如下所示的样式组件中使用主题间距值,但没有成功。 当我第一次创建它时,样式被应用于按钮。但是现在,没有应用任何样式!

你可以在这里看到它:sandbox

import React from "react";
import styled, { ThemeProvider } from "styled-components";
import {
  createMuiTheme,
  ThemeProvider as MuiThemeProvider,
  darken
} from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const customTheme = createMuiTheme({
  palette: {
    primary: {
      main: "#6772e5"
    }
  },
  spacing: 8
});
const StyledButton = styled(Button)`
  ${({ theme }) => `
    background-color: ${theme.palette.primary.main};
    color: #fff;
    box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
    padding-left: 20px;
    padding-right: ${theme.spacing(2)};
    font-size: 13px;
    &:hover {
      background-color: ${darken(theme.palette.primary.main, 0.2)};
    }  
  `}
`;

export default function App() {
  return (
    <MuiThemeProvider theme={customTheme}>
      <ThemeProvider theme={customTheme}>
        <StyledButton>Customized</StyledButton>
      </ThemeProvider>
    </MuiThemeProvider>
  );
}

【问题讨论】:

  • 使用StylesProvider 组件,如图所示here

标签: css reactjs material-ui styled-components


【解决方案1】:

您的 styled-component 样式被默认的 JSS 样式覆盖。默认情况下,JSS 样式被注入到 &lt;head&gt; 的底部(更高的 CSS 特异性)。您可以通过将组件树放在&lt;StylesProvider injectFirst&gt; 中来告诉 MUI 覆盖 JSS 样式。见controlling priority

// tell MUI to inject JSS style first, so styled-component can override it
<StylesProvider injectFirst>
  <MuiThemeProvider theme={customTheme}>
    <ThemeProvider theme={customTheme}>
      <StyledButton>Customized</StyledButton>
    </ThemeProvider>
  </MuiThemeProvider>
</StylesProvider>

【讨论】:

  • 很好!但是 padding-right 仍然没有使用 theme.spacing 值。如何解决?
  • @killjoy theme.spacing(2) 返回一个没有单位的数字。您需要在末尾附加 px 单元。我已经为你更新了现场演示。
  • 我可以在每个组件基础上使用 吗?不在应用范围内。或者也许我可以为特定组件覆盖此行为?
  • @killjoy No.injectFirst用于设置injectFirstNode,这是一个模块范围的变量,所以只有app范围。 Source
猜你喜欢
  • 2020-05-08
  • 2019-11-28
  • 2021-05-23
  • 2019-12-30
  • 2021-01-08
  • 2020-06-24
  • 2018-09-14
  • 2020-08-01
  • 1970-01-01
相关资源
最近更新 更多