如何使用样式化的组件和Material-UI对组件进行主题设置?

问题描述 投票:1回答:2

是否可以使用TypeScriptMaterial-UI“ theme” -prop与styled-components一起使用?

示例材料-UI代码:

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

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

const Wrapper = styled.div`
  background: ${props => props.theme.palette.primary.main};
`;
reactjs typescript material-ui styled-components
2个回答
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>
  );
}

Edit Use theme with styled-components

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

来自文档的withTheme HOC部分。


-1
投票

我认为没有预定的方式。如果您更喜欢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);
  `,
});
© www.soinside.com 2019 - 2024. All rights reserved.