之前,在 Material-UI v4 中,我有这段代码
const { customPadding } = props;
const classes = useStyles({
padding: customPadding,
} as any);
将 props 传递给元素的类。
但是 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>
);
}
现场演示
关于reactjs - MUI v5 使用 styled() 将 props 传递给 CSS 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308658/