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

Remix框架使用Styled-components遇Prop className did not match错误求助

Remix中解决Styled-components的"Prop className did not match" SSR错误

出现这个错误的核心原因是服务端渲染时,styled-components在服务端生成的className与客户端生成的不一致,需要配置SSR同步规则来解决。

解决步骤:

  1. 安装依赖
    安装babel-plugin-styled-components确保两端className生成规则一致:
npm install --save-dev babel-plugin-styled-components

(使用yarn/pnpm可替换为对应命令)

  1. 配置Babel
    在项目根目录创建babel.config.json,添加styled-components插件配置:
{
  "presets": ["@remix-run/dev"],
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}
  1. 修改Remix根组件(app/root.jsx)
    集成styled-components的SSR样式收集与注入逻辑:
import { ServerStyleSheet, StyleSheetManager } from "styled-components";
import {
  Links,
  LiveReload,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
} from "@remix-run/react";
import { useLoaderData } from "@remix-run/react";
import { json } from "@remix-run/node";

// 服务端收集样式
export async function loader() {
  const sheet = new ServerStyleSheet();
  return json({
    styles: sheet.getStyleElement(),
  });
}

export default function App() {
  const { styles } = useLoaderData();

  return (
    <html lang="zh-CN">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <Links />
        {/* 注入服务端生成的样式标签 */}
        {styles}
      </head>
      <body>
        {/* 确保客户端使用与服务端一致的样式规则 */}
        <StyleSheetManager sheet={new ServerStyleSheet().instance}>
          <Outlet />
          <ScrollRestoration />
          <Scripts />
          <LiveReload />
        </StyleSheetManager>
      </body>
    </html>
  );
}

完成以上配置后,你的原有组件代码无需修改,服务端与客户端生成的className将保持一致,错误即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:45:31