【问题标题】:Cannot read properties of undefined (reading 'up'), using MakeStyle无法使用 MakeStyle 读取未定义的属性(读取“向上”)
【发布时间】:2021-12-30 23:23:03
【问题描述】:

我正在尝试创建自定义样式:

import { makeStyles } from '@mui/styles';
import { createTheme,  } from '@mui/material/styles';


const theme = createTheme();
const widthStyle = makeStyles((theme) => ({
    wrapper: {
       position: 'relative',
       [theme.breakpoints.up('sm')]: {
            width: '95%'
       },
       [theme.breakpoints.up('md')]: {
            width: '75%'
       }
    }
}));

const Wrapper= () => {
    const classes = widthStyle(theme);
    return (  <div className={classes.wrapper}></div>);
}

但是,我得到了错误:

TypeError: Cannot read properties of undefined (reading 'up')

为什么会这样?

我的依赖是:

 "@mui/material": "^5.2.5",
    "@mui/styles": "^5.2.3",

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    makeStyles & withStyle 现在根据 MUI 团队考虑 legacy。现在有了 MUI5,您可以以更好的方式做到这一点。 styled-component 已包含在 @mui/material/styles 包中。

    您可以通过任何方式执行此操作,也可以使用普通的styled-component 执行此操作。请参考here了解更多。

    • 您甚至可以自定义 MUI 组件本身
    • 或(新功能),将样式放在 MUI 团队提供的 unstyled MUI 组件选项上 (reference)
    • 顺便说一句,您不必为了使用default theme options 而导入createTheme。只需确保导入 import { ThemeProvider } from '@mui/material/styles' 并放入主 app.js 文件 (reference)。
    import { styled } from '@mui/material/styles';
    
    const Wrapper = styled('div')(({ theme }) => ({
      position: 'relative',
      [theme.breakpoints.up('sm')]: {
        width: '95%'
      },
      [theme.breakpoints.up('md')]: {
        width: '75%'
      },
      '.wrapper2': {
        backgroundColor: theme.palette.warning.main
      }
    }));
    
    const Wrapper= () => {
      return (  
        <Wrapper>
          Something here
          <div className="wrapper2">
            Something here too
          </div>
        </Wrapper>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2023-03-11
      • 2022-01-15
      • 2021-12-31
      • 2021-12-13
      • 2021-11-28
      • 2021-11-15
      相关资源
      最近更新 更多