reactjs - 如何使用 styled-components 和 Material-UI 对组件进行主题化?

标签 reactjs typescript material-ui styled-components

有没有可能使用 Material -UI “主题”-prop 与 样式组件 使用 typescript ?

示例 Material-UI 代码:

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

现在我想用样式组件替换这段代码。
我已经测试了以下实现(和其他类似的实现)但没有成功:
const Wrapper = styled.div`
  background: ${props => props.theme.palette.primary.main};
`;

最佳答案

您可以使用withTheme将主题作为 Prop 注入(inject)。

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文档的一部分。

关于reactjs - 如何使用 styled-components 和 Material-UI 对组件进行主题化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59831437/

相关文章:

node.js - 是否可以使用 SAML2 在 ReactJs 应用程序中实现 SSO?如果可能怎么办?

javascript - es6调用扩展组件函数

reactjs - 即使在执行 fetch.mockResponse 之后仍使用 Jest 实际获取被调用

typescript - 受歧视的联合是否只适用于文字类型?

typescript - ESLint 在包含的 tsconfig 文件上抛出错误

javascript - VSCode 自动导入 - 如何强制 Material-UI 全路径导入

reactjs - 将 Material-ui 自定义主题与 redux 结合使用

html - 如何使用 Thymeleaf th :text in reactJS

angular - 如何将 Firebase 中的查询快照转换为不同的对象?

html - 如何在没有id或class的输入字段中添加CSS?