TypeError:无法读取 null 的属性(读取“useContext”)-Material UI

问题描述 投票:0回答:1

我在我的项目中使用MUI(Material UI)。
我尝试使用的组件是

Button

检查其官方组件文档这里
发生错误的代码:

import * as React from 'react';
import Button from '@mui/material/Button';
import DeleteIcon from '@mui/icons-material/Delete';
import SendIcon from '@mui/icons-material/Send';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';

export default function IconLabelButtons() {
  return (
    <>
      <Button variant="outlined" startIcon={<ShoppingCartIcon />} sx={{color:'grey'}}>
        Add To Cart
      </Button>
      <Button variant="contained" endIcon={<ShoppingCartIcon />} sx={{ color: 'white', backgroundColor:'grey' }}>
        Add To Cart
      </Button>
    </>
  );
}


完整错误消息:

Cannot read properties of null (reading 'useContext')
TypeError: Cannot read properties of null (reading 'useContext')
    at Object.useContext (http://localhost:3001/static/js/bundle.js:77496:25)
    at useDefaultProps (http://localhost:3001/static/js/bundle.js:70496:50)
    at useDefaultProps (http://localhost:3001/static/js/bundle.js:67954:91)
    at SvgIcon (http://localhost:3001/static/js/bundle.js:68093:96)
    at renderWithHooks (http://localhost:3001/static/js/bundle.js:42667:22)
    at updateForwardRef (http://localhost:3001/static/js/bundle.js:45916:24)
    at beginWork (http://localhost:3001/static/js/bundle.js:47977:20)
    at HTMLUnknownElement.callCallback (http://localhost:3001/static/js/bundle.js:32923:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3001/static/js/bundle.js:32967:20)
    at invokeGuardedCallback (http://localhost:3001/static/js/bundle.js:33024:35)

如果我从按钮标签中删除

startIcon
startIcon
选项,此代码可以正常工作。
工作代码:

import * as React from 'react';
import Button from '@mui/material/Button';
import DeleteIcon from '@mui/icons-material/Delete';
import SendIcon from '@mui/icons-material/Send';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';

export default function IconLabelButtons() {
  return (
    <>
      <Button variant="outlined"  sx={{color:'grey'}}>
        Add To Cart
      </Button>
      <Button variant="contained"  sx={{ color: 'white', backgroundColor:'grey' }}>
        Add To Cart
      </Button>
    </>
  );
}

但是,我想使用这两个选项。
我已经在项目中安装了

mui/material
mui/icons-material
依赖项。仍然面临上述问题。

社区中的任何人都可以帮我解决这个问题吗?

javascript reactjs material-ui jsx
1个回答
0
投票

如果您检查官方文档提供的链接。
它的版本是

6.1.1

因此,我尝试使用以下命令更新项目中使用的两个 deps 的版本:

npm install @mui/material@latest @mui/icons-material@latest

这样做修复了错误。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.