使用react-grid-layout与Material UI Paper组件时遇createContext报错求助
解决React + Material UI + react-grid-layout的Context错误
嘿,我马上帮你搞定这个问题!你遇到的TypeError: react__WEBPACK_IMPORTED_MODULE_0___default.a.createContext is not a function错误其实是版本不兼容和代码混用导致的,具体原因和修复步骤如下:
核心问题:React版本过低
你项目里的React是15.1.0,这个版本完全没有createContext API——而你使用的@material-ui/core@4.7.0(Material UI v4)依赖React 16.8及以上版本(因为用到了Context API和Hooks特性),这直接触发了报错。
修复步骤
1. 升级React和React DOM到兼容版本
打开终端,执行以下命令升级到支持Material UI v4的React稳定版本(推荐16.8.0及以上):
npm install react@^16.8.0 react-dom@^16.8.0 --save
2. 修正Material UI的导入错误
你的代码里混用了旧版Material UI(material-ui包)和新版(@material-ui/core)的导入,这会导致版本冲突:
- Home组件:把Paper的导入从旧版包改成新版:
// 替换前 import { Paper } from 'material-ui'; // 替换后 import Paper from '@material-ui/core/Paper'; - App组件:
MuiThemeProvider在Material UI v4里属于@material-ui/core/styles,不是旧版的material-ui/styles,同时建议显式创建主题实例:// 替换前 import { MuiThemeProvider } from 'material-ui/styles'; // 替换后 import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; // 在App组件里添加主题实例 class App extends React.Component { render() { const theme = createMuiTheme(); // 创建默认主题 return ( <MuiThemeProvider theme={theme}> <Router> <Route path="/" component={Home}/> </Router> </MuiThemeProvider> ); } }
3. 修正类组件的样式使用方式
你用了makeStyles(Hooks专属的样式方案)但在类组件Home里使用,这是错误的——makeStyles只能用于函数组件,类组件要搭配withStyles和普通样式对象:
// 替换前的useStyles const useStyles = makeStyles(theme => ({ root: { padding: theme.spacing(3,2), }, })); // 替换成普通样式对象 const styles = theme => ({ root: { padding: theme.spacing(3, 2), }, }); // 保持导出方式不变 export default withStyles(styles)(Home);
4. 确保GridLayout子项的key属性正确
你的GridLayout子项的key属性放在了Typography上,应该放在Paper组件上,这样react-grid-layout才能正确识别每个网格项:
<GridLayout className="layout" layout={layout} cols={12} rowHeight={30} width={1200}> <Paper key="a" className={classes.root}> <Typography variant="h5" component="h3"> This is a set of paper! </Typography> </Paper> <Paper key="b" className={classes.root}> <Typography variant="h5" component="h3"> This is a set of paper! </Typography> </Paper> <Paper key="c" className={classes.root}> <Typography variant="h5" component="h3"> This is a set of paper! </Typography> </Paper> </GridLayout>
完成以上步骤后,重新启动项目,应该就能正常运行了!
内容的提问来源于stack exchange,提问作者Ido Magor
相关产品推荐
相关产品推荐

