【问题标题】:MUI v5 passing props to CSS theme using styled()MUI v5 使用 styled() 将道具传递给 CSS 主题
【发布时间】: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 - ${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 中实现这一点?

【问题讨论】:

    标签: reactjs material-ui emotion


    【解决方案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>
      );
    }
    

    现场演示

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2021-11-23
      • 2019-10-07
      • 2021-12-19
      • 1970-01-01
      • 2022-01-24
      • 2022-01-07
      • 2021-12-08
      • 2021-12-06
      相关资源
      最近更新 更多