繁体   English   中英

在样式化组件中使用 Material-ui 主题

[英]Using Material-ui theme in styled component

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

你可以在这里看到它: 沙盒

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

您的样式组件 styles 被默认 JSS styles 覆盖。 默认情况下,JSS styles 被注入到<head>的底部(更高的 CSS 特异性)。 你可以告诉 MUI 覆盖 JSS styles,方法是将你的组件树放在<StylesProvider injectFirst>中。 请参阅控制优先级

// 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>

编辑 67232779/using-material-ui-theme-in-styled-component

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM