有没有可能使用 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>
);
}
有关 TypeScript 方面的入门,请参阅此演示:https://codesandbox.io/s/xyh60
这是来自 withTheme HOC文档的一部分。
关于reactjs - 如何使用 styled-components 和 Material-UI 对组件进行主题化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59831437/