reactjs - MUI v5 使用 styled() 将 props 传递给 CSS 主题

标签 reactjs material-ui emotion

之前,在 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>
  );
}

现场演示

Codesandbox Demo

关于reactjs - MUI v5 使用 styled() 将 props 传递给 CSS 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308658/

相关文章:

css - 如何使用情感 CSS 覆盖 React 组件的 CSS?

reactjs - 如何为一组组件创建一个动态的 React 钩子(Hook)数组

javascript - 与 Webpack Dev Server 一起使用时,Webpack 不生成包

reactjs - 获取 window.scroll 上的 redux 状态

javascript - 找不到模块 : Can't resolve '@mui/icons-material/FileDownload'

reactjs - 在我的 React 应用程序中使用 @emotion/core 时出错

javascript - 使用lodash groupBy函数对数组中的对象进行分类

javascript - 在 MaterialUI 和 React.js 中为 Autocomplete 分配默认值

css - MUI 选择组件填充 (ReactJS)

javascript - 创建新组件并从 styled-component 继承样式