How to theme components with styled-components and Material-UI?

戏子无情 提交于 2021-01-27 18:48:37

问题


Is there a possibility to use the Material-UI "theme"-prop with styled-components using TypeScript?

Example Material-UI code:

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    background: theme.palette.primary.main,
  },
}));

Now I want to replace this code with styled-components.
I have tested the following implementation (and other similar implementations) without success:

const Wrapper = styled.div`
  background: ${props => props.theme.palette.primary.main};
`;

回答1:


You can use withTheme to inject the theme as a prop.

import React from "react";
import { withTheme } from "@material-ui/core/styles";
import styled from "styled-components";

const StyledDiv = withTheme(styled.div`
  background: ${props => props.theme.palette.primary.main};
  color: ${props => props.theme.palette.primary.contrastText};
`);
export default function App() {
  return (
    <StyledDiv>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </StyledDiv>
  );
}

For a start on the TypeScript aspects, see this demo: https://codesandbox.io/s/xyh60

This is from the withTheme HOC portion of the documentation.




回答2:


I wanted a similar set of requirements (MUI, styled-components, theme & typescript). I got it working, but I'm sure it could be prettier:

import React from "react";
import styled from "styled-components";
import { Theme, useTheme } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const StyledCustomButton: React.FC<{
  theme: Theme;
}> = styled(({ ...props }) => <Button {...props}>Test</Button>)`
  && {
    padding-bottom: ${(props) => props.theme.spacing(2)}px;
  }
`;

const CustomButton: React.FC = () => {
  const theme: Theme = useTheme();
  return <StyledCustomButton theme={theme} />;
};

export default CustomButton;



回答3:


I think no intended way. If you prefer the css way of writing then maybe consider this https://material-ui.com/styles/advanced/#string-templates

The example is

const useStyles = makeStyles({
  root: `
    background: linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%);
    border-radius: 3px;
    font-size: 16px;
    border: 0;
    color: white;
    height: 48px;
    padding: 0 30px;
    box-shadow: 0 3px 5px 2px rgba(255, 105, 135, 0.3);
  `,
});


来源:https://stackoverflow.com/questions/59831437/how-to-theme-components-with-styled-components-and-material-ui

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