如何使用样式化组件和Material-UI为组件设置主题?

时间:2020-01-20 21:59:31

标签: reactjs typescript material-ui styled-components

是否可以使用 TypeScript Material-UI “主题” -prop与样式化组件一起使用?

示例材料UI代码:

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

现在,我想将此代码替换为样式组件。
我已经测试了以下实现(以及其他类似的实现),但均未成功:

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

3 个答案:

答案 0 :(得分:1)

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

def string(f):
    letters = ['a','b','c','d']
    error=False
    for i in f:
        if i not in letters:
            error=True
            print('error')
            break
    else:
        print('ok')

Edit Use theme with styled-components

有关TypeScript方面的开始,请参见以下演示:https://codesandbox.io/s/xyh60

这来自文档的withTheme HOC部分。

答案 1 :(得分:0)

我想要一套类似的要求(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;

答案 2 :(得分:-1)

我认为没有预定的方式。如果您喜欢CSS的书写方式,则可以考虑使用enter image description here

示例是

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