reactjs - MUI v5 使用 styled() 将道具传递给 CSS 主题
问题描述
以前,在 Material-UI v4 中,我有这段代码
const { customPadding } = props;
const classes = useStyles({
padding: customPadding,
} as any);
将道具传递给元素的类。
但是 v5 使用emotion
而不是 JSS,我在其中做类似的事情。
const StyledContainer = styled(Container)(({theme}: any) => ({
[`&.${classes.FullPageLayoutRoot}`]: (props: any) => ({
minHeight: `calc(100vh - ${appBarHeight}px - ${theme.spacing(1)} - 1px)`,
display: 'flex',
}),
[`&.${classes.middle}`]: {
alignItems: 'center',
},
[`& .${classes.paper}`]: (props: any) => ({
backgroundColor: grey[800],
marginBottom: theme.spacing(1),
padding: theme.spacing(props.padding),
minWidth: '100%',
})
}));
...
return(
<StyledContainer maxWidth={maxWidth} fixed className={clsx(classes.FullPageLayoutRoot, {
[classes.middle]: middle,
})}>
<Paper className={clsx(classes.paper, classes.padding, className)} {...PaperProps} >
{content}
</Paper>
</StyledContainer>
)
我将如何在 Material-UI v5 中实现这一点?
解决方案
它们与theme
回调中的属性一起传递:
const MyDiv = styled("div", {
// indicate that this prop name should be used to conditionally
// style the component only and should not be spread to the DOM element.
shouldForwardProp: (propName) => propName !== "isRed"
})(({ theme, isRed }) => ({
backgroundColor: isRed ? "red" : theme.palette.primary.main
}));
export default function ThemeUsage() {
return (
<MyDiv isRed>Styled div with theme</MyDiv>
);
}
现场演示
推荐阅读
- javascript - Webpack 模块规则测试:匹配包含特定参数的文件
- gradle - 使用 Groovy 应用和测试代码结合 jlink 解决方案来捆绑 JavaFX
- c - 如何在C中将char添加到字符串的末尾?
- reactjs - 无需登录即可打开 PowerBI 页面
- node.js - SheetJS 总是抛出相同的输出
- git - 如何结合 Ansible 在 Git 中配置/描述 Web 应用程序的部署
- javascript - 可以用 React Hooks 定义嵌套组件吗?
- assembly - 64 位汇编中的计算能力
- html - 如何使用 sed 删除 HTML 中的 html 标签、脚本、空行?
- python - How can i convert string to Kivy id's value?