You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:22:19