如何在Material-UI v5中通过styled()向CSS主题传递自定义props
Material-UI v5 向styled组件传递props的正确实现
MUI v5基于emotion的styled API支持直接向样式回调传递自定义props,你可以按以下方式改造代码:
第一步:定义带自定义props的StyledContainer
import { styled } from '@mui/material/styles'; import Container from '@mui/material/Container'; import Paper from '@mui/material/Paper'; import { grey } from '@mui/material/colors'; // 自定义的appBarHeight可以提为常量 const appBarHeight = 64; const StyledContainer = styled(Container, { // 配置shouldForwardProp,避免自定义props透传给底层DOM元素触发警告 shouldForwardProp: (prop) => !['padding', 'middle'].includes(prop), })(({ theme, padding, middle }) => ({ // 根元素样式,不需要再手动匹配className minHeight: `calc(100vh - ${appBarHeight}px - ${theme.spacing(1)} - 1px)`, display: 'flex', // middle属性直接控制样式,不需要额外加className ...(middle && { alignItems: 'center', }), // 内部Paper的样式,直接用传入的padding参数 '& .MuiPaper-root': { backgroundColor: grey[800], marginBottom: theme.spacing(1), padding: theme.spacing(padding), minWidth: '100%', } }));
第二步:组件内使用时传入自定义props
function YourComponent(props) { const { customPadding, middle, maxWidth, className, PaperProps, content } = props; return( <StyledContainer maxWidth={maxWidth} fixed // 直接传入自定义的padding和middle参数 padding={customPadding} middle={middle} > <Paper className={className} {...PaperProps} > {content} </Paper> </StyledContainer> ); }
兼容原有自定义className的方案
如果你的项目里依赖之前的classes命名规范,也可以用v5兼容的JSS方案:
import { makeStyles } from '@mui/styles'; const useStyles = makeStyles()((theme, { padding }) => ({ FullPageLayoutRoot: { minHeight: `calc(100vh - ${appBarHeight}px - ${theme.spacing(1)} - 1px)`, display: 'flex', }, middle: { alignItems: 'center', }, paper: { backgroundColor: grey[800], marginBottom: theme.spacing(1), padding: theme.spacing(padding), minWidth: '100%', } })); // 组件内使用 function YourComponent(props) { const { customPadding, middle, maxWidth, className, PaperProps, content } = props; const classes = useStyles({ padding: customPadding }); return( <Container maxWidth={maxWidth} fixed className={clsx(classes.FullPageLayoutRoot, { [classes.middle]: middle })} > <Paper className={clsx(classes.paper, className)} {...PaperProps} > {content} </Paper> </Container> ); }
内容的提问来源于stack exchange,提问作者cclloyd
相关产品推荐
相关产品推荐

