Using Material-UI System with Default Components

风流意气都作罢 提交于 2021-02-04 20:45:10

问题


Is it possible to use Material-UI System with the default Material UI components? For example, this currently does not work:

<AppBar bgColor="secondary.main"  p={{ xs: 2, sm: 3, md: 4 }}>...</AppBar>

I am wondering, though, is there a way to get this to work (not just for AppBar, but for any Material UI component)? I.e., is there a way to integrate System with the default Material UI components?

If so, how?

Thanks.


回答1:


The Box component can be used to add the Material-UI System features to other components by using its component prop. One caveat is that if you try to change styling that is explicitly controlled by the component, you may run into specificity issues. For instance the styling of the background color on the Button in my example below doesn't work correctly if you flip the order of the Button and Box imports since this causes the order of their styles in the <head> to also be flipped.

import React from "react";
import styled, { ThemeProvider as SCThemeProvider } from "styled-components";
import { useTheme, StylesProvider } from "@material-ui/core/styles";
import MuiAppBar from "@material-ui/core/AppBar";
import Button from "@material-ui/core/Button";
import Box from "@material-ui/core/Box";

const AppBar = styled(MuiAppBar)`
  background-color: red;
  ${props => props.theme.breakpoints.up("sm")} {
    background-color: orange;
  }
  ${props => props.theme.breakpoints.up("md")} {
    background-color: yellow;
    color: black;
  }
  ${props => props.theme.breakpoints.up("lg")} {
    background-color: green;
    color: white;
  }
`;
export default function App() {
  const muiTheme = useTheme();
  return (
    <StylesProvider injectFirst>
      <SCThemeProvider theme={muiTheme}>
        <Box component={AppBar} p={{ xs: 2, sm: 3, md: 4, lg: 5 }}>
          Sample AppBar 1
        </Box>
        <div style={{ height: "100px" }} />
        <Box component={Button} bgcolor="secondary.main">
          Sample Button
        </Box>
      </SCThemeProvider>
    </StylesProvider>
  );
}

Related answer: Material-UI Grid does not hide whe use Display



来源:https://stackoverflow.com/questions/59922817/using-material-ui-system-with-default-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!