Next.js使用Material UI的withStyles出现服务端客户端类名不一致警告
方案1:固定withStyles的类名前缀(最快生效)
给你的withStyles配置添加name参数,强制生成固定规则的类名,避免服务端和客户端随机生成的类名哈希不一致:
const LikeButton = withStyles((theme: Theme) => ({ root: { // 原有样式保持不变 color: "#666666", fontSize: "1.3125rem!important", fontWeight: 700, maxWidth: "51px!important", width: "51px!important", minWidth: "51px!important", backgroundColor: "#fcfbfa", marginLeft: "1rem", border: "1px solid #dcdcdc", "& svg": { fill: "currentColor", color: "currentColor", }, "&:hover": { color: theme.palette.secondary.main, backgroundColor: "#fcfbfa", }, "&.Mui-disabled": { backgroundColor: "#e6e6e6", color: "#666666!important", }, }, // 新增下方配置项 }), { name: 'CustomLikeButton' })(Button);
该方案可直接解决90%的类名不一致警告,无需修改其他配置。
方案2:完善Next.js的MUI SSR配置
如果方案1未生效,说明缺少MUI服务端渲染样式同步配置,根据你使用的Next.js版本调整:
若使用Next.js Pages Router(pages目录结构)
在pages/_document.tsx(无该文件则新建)添加以下配置,统一收集服务端渲染的MUI样式:
import Document, { Html, Head, Main, NextScript } from 'next/document'; // MUI v4使用下方导入 import { ServerStyleSheets } from '@material-ui/core/styles'; // MUI v5使用下方导入 // import { ServerStyleSheet } from '@mui/styles'; export default class MyDocument extends Document { render() { return ( <Html lang="zh-CN"> <Head /> <body> <Main /> <NextScript /> </body> </Html> ); } } MyDocument.getInitialProps = async (ctx) => { const sheets = new ServerStyleSheets(); const originalRenderPage = ctx.renderPage; ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheets.collect(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()], }; };
若使用Next.js 13+ App Router(app目录结构)
- 所有使用withStyles的组件顶部都要添加
'use client'指令,标记为客户端组件 - 在全局layout中配置MUI样式缓存,避免重复生成类名
方案3:升级样式写法(长期修复)
withStyles是MUI v4的遗留API,v5之后官方更推荐使用styled API,和Next.js兼容性更好,可直接改写为:
import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; const LikeButton = styled(Button)(({ theme }) => ({ // 原有样式直接复制即可 color: "#666666", fontSize: "1.3125rem!important", fontWeight: 700, maxWidth: "51px!important", width: "51px!important", minWidth: "51px!important", backgroundColor: "#fcfbfa", marginLeft: "1rem", border: "1px solid #dcdcdc", "& svg": { fill: "currentColor", color: "currentColor", }, "&:hover": { color: theme.palette.secondary.main, backgroundColor: "#fcfbfa", }, "&.Mui-disabled": { backgroundColor: "#e6e6e6", color: "#666666!important", }, }));
该写法无需额外配置,天生兼容Next.js的SSR逻辑,不会出现类名不匹配问题。
内容的提问来源于stack exchange,提问作者amin71
相关产品推荐
相关产品推荐

