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

MUI v5.0.0与NextJS+styled-components集成时injectFirst不生效问题

解决方案

1. 替换_app.tsx中的样式Provider

MUI v5默认不再使用@mui/styles作为样式方案,你当前使用的StylesProvider属于遗留API,无法覆盖新的MUI组件样式注入逻辑,需要替换为StyledEngineProvider:
首先调整导入:

- import { StylesProvider } from '@mui/styles';
+ import { StyledEngineProvider } from '@mui/material/styles';

然后替换外层Provider配置:

- <StylesProvider injectFirst>
+ <StyledEngineProvider injectFirst>
    <ThemeProvider theme={setTheme}>
      {/* 原有内容保持不变 */}
    </ThemeProvider>
- </StylesProvider>
+ </StyledEngineProvider>

2. 修正_document.js的服务端样式收集逻辑

你当前使用的ServerStyleSheets来自旧的@mui/styles包,无法收集MUI v5核心组件的样式,需要替换为新包的导出,你当前返回样式的顺序是正确的:先返回MUI的样式元素,再返回styled-components的样式元素,可以保证后者优先级更高:

- import { ServerStyleSheets } from '@mui/styles';
+ import { ServerStyleSheets } from '@mui/material/styles';

3. 修复package.json依赖版本冲突

你当前依赖的@emotion/styled版本为v10,和@emotion/react的v11版本不匹配,会导致样式注入异常,升级到对应版本即可:

"dependencies": {
-  "@emotion/styled": "^10.0.27",
+  "@emotion/styled": "^11.4.1",
}

如果项目完全不使用emotion作为样式方案,也可以直接卸载@emotion/react和@emotion/styled包,MUI会自动使用你配置的styled-engine-sc作为唯一样式引擎。

4. 可选:局部优先级提升

如果修改完上述配置后仍有个别组件样式被MUI覆盖,可以在styled组件的样式代码前加&&提升优先级:

const StyledButton = styled(MuiButton)`
  && {
    background: #fff;
  }
`

内容的提问来源于stack exchange,提问作者kevin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:15:03