如何使用样式化的组件和Material-UI对组件进行主题设置? [英] How to theme components with styled-components and Material-UI?
本文介绍了如何使用样式化的组件和Material-UI对组件进行主题设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用 TypeScript 将 Material-UI 主题" -prop与样式化组件一起使用?
示例材料UI代码:
const useStyles = makeStyles((theme:Theme)=>({根: {背景:theme.palette.primary.main,},}));
现在,我想将此代码替换为样式组件.
我已经测试了以下实现(以及其他类似的实现),但均未成功:
const Wrapper = styled.div`背景:$ {props =>props.theme.palette.primary.main};`;
解决方案
您可以使用
有关TypeScript方面的开始,请参见以下演示: https://codesandbox.io/s/xyh60
这来自 withtheme HOC 文档的一部分.
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};
`;
解决方案
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.
这篇关于如何使用样式化的组件和Material-UI对组件进行主题设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文