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

同一组件混用formik-material-ui与MUI TextField出现className不匹配警告

问题原因

这个警告是Next.js服务端渲染(SSR)阶段和客户端hydrate阶段,Material UI v4动态生成的样式类名ID计数不一致导致的。你同时混用了两种封装的TextField组件:formik-material-ui内置的TextField、你自己用fieldToTextField封装的原生MUI TextField,两者在服务端和客户端的渲染顺序、样式注入顺序存在差异,只有outlined变体因为依赖内部的PrivateNotchedOutline动态类名,才会触发该警告。

解决方案

方案1:统一TextField封装方式(推荐,成本最低)

不要同时混用两种封装的TextField,全项目统一用其中一种即可:

  • 要么所有Formik绑定的TextField都直接用formik-material-ui导出的版本
  • 要么所有都用你自己基于fieldToTextField封装的TextFieldFormik组件

方案2:手动指定组件ID

给每个outlined变体的TextField显式指定唯一的id属性,让MUI基于你指定的ID生成类名,替代默认的自增数字ID,避免两端计数不一致:

<Field
  component={TextField}
  id="first" // 新增唯一id
  name="first"
  variant="outlined"
  fullWidth
  label="first"
/>

<Field
  component={TextFieldFormik}
  id="second" // 新增唯一id
  name="second"
  variant="outlined"
  fullWidth
  label="second"
/>

方案3:配置Next.js自定义_document修复MUI SSR样式匹配

如果以上方案都不适用,你可以在项目pages目录下新增_document.js,统一处理MUI服务端样式注入,从根源解决类名不匹配问题:

// pages/_document.js
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/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()],
  };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:27:04