【问题标题】:How to theme components with styled-components and Material-UI?如何使用 styled-components 和 Material-UI 对组件进行主题化?
【发布时间】:2020-05-06 22:38:57
【问题描述】:

是否有可能通过 TypeScriptMaterial-UI “主题”-prop 与 styled-components 一起使用?

示例 Material-UI 代码:

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

现在我想用 styled-components 替换这段代码。
我已经测试了以下实现(和其他类似的实现)但没有成功:

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

【问题讨论】:

    标签: reactjs typescript material-ui styled-components


    【解决方案1】:

    您可以使用withTheme 将主题作为道具注入。

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

    有关 TypeScript 方面的入门,请参阅此演示:https://codesandbox.io/s/xyh60

    这是来自文档的withTheme HOC 部分。

    【讨论】:

    • 你能更详细地使用 TypeScript 吗?
    • 我自己不使用 TypeScript,所以帮不上什么忙。
    【解决方案2】:

    我想要一组类似的需求(MUI、样式组件、主题和打字稿)。我得到了它的工作,但我相信它会更漂亮:

    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】:

      我认为没有故意的方式。如果您更喜欢 css 编写方式,那么可以考虑这个https://material-ui.com/styles/advanced/#string-templates

      例子是

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

      【讨论】:

        猜你喜欢
        • 2021-01-29
        • 2018-09-14
        • 2021-05-19
        • 2020-05-14
        • 2020-11-16
        • 2019-06-27
        • 2019-08-02
        • 2020-03-28
        • 2020-05-12
        相关资源
        最近更新 更多