MUI v5 使用 styled() 将道具传递给 CSS 主题
Posted
技术标签:
【中文标题】MUI v5 使用 styled() 将道具传递给 CSS 主题【英文标题】:MUI v5 passing props to CSS theme using styled() 【发布时间】:2021-11-17 08:42:44 【问题描述】:以前,在 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 - $appBarHeightpx - $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 中实现这一点?
【问题讨论】:
【参考方案1】:它们与回调中的 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>
);
现场演示
【讨论】:
以上是关于MUI v5 使用 styled() 将道具传递给 CSS 主题的主要内容,如果未能解决你的问题,请参考以下文章
样式化的 MUI 无法在 typescript 中将组件道具传递给 Typography
MUI v5:失败的道具类型:`Grid`的道具`direction`只能与`container`道具一起使用