在Next.js中使用Material UI简单分页组件为何报错?
问题:Next.js集成Material UI Pagination组件触发服务端错误
我在Next.js项目中尝试使用Material UI的Pagination组件,哪怕只添加一个基础的<Pagination>标签都会报错。代码如下:
import Layout from "../components/Layout"; import Pagination from "@mui/material/Pagination"; export default function Blah() { return ( <Layout> <Pagination count={10} color="primary" /> </Layout> ); }
访问页面时出现服务器错误:
Server Error TypeError: Cannot read properties of undefined (reading 'focus') This error happened while generating the page. Any console logs will be displayed in the terminal window. Call Stack PaginationItemPage.theme.theme file:///workspace/NickBlog/node_modules/@mui/material/node/PaginationItem/PaginationItem.js (107:59) transformedStyleArg file:///workspace/NickBlog/node_modules/@mui/system/createStyled.js (199:40) handleInterpolation
解决方案
这个错误的核心原因是Material UI组件需要在ThemeProvider的包裹下才能访问主题配置,Next.js的服务端渲染环境中,缺少主题上下文会导致组件无法读取theme对象中的focus相关属性。
1. 全局配置ThemeProvider
在Next.js的_app.js(或_app.tsx)中全局添加ThemeProvider,确保所有页面组件都能获取到主题上下文:
import { ThemeProvider, createTheme } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; // 可根据需求自定义主题配置 const theme = createTheme(); export default function MyApp({ Component, pageProps }) { return ( <ThemeProvider theme={theme}> {/* CssBaseline用于重置全局样式,可选但推荐添加 */} <CssBaseline /> <Component {...pageProps} /> </ThemeProvider> ); }
2. 检查Layout组件的主题包裹情况
如果你的Layout组件已经包含了ThemeProvider,确认其配置正确,避免重复包裹或主题对象未正确传递。
3. 排查版本兼容性
如果上述方法无效,可能是Material UI与Next.js的版本不兼容,尝试更新到最新稳定版:
npm update @mui/material @emotion/react @emotion/styled next
内容的提问来源于stack exchange,提问作者Nick Hodges
相关产品推荐
相关产品推荐

