在 next.js 14 中,传统 css-in-js(如 styled-components)在服务端渲染时会导致样式闪烁,是因为服务端无法同步提取并注入所有动态生成的样式,导致客户端 hydration 后样式才生效。要解决这个问题,必须使用支持服务端渲染的 css-in-js 方案,例如通过 `serverstylesheet` 在服务端预取样式并注入到 html 中。

为什么 styled-components 在服务端会丢失样式?
styled-components 在服务端渲染时,如果不使用 `ServerStyleSheet`,动态生成的样式类名不会被包含在初始 HTML 中。这导致页面加载时用户看到无样式的布局,直到客户端 JavaScript 执行并重新应用样式,从而产生视觉闪烁。

import React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheet } from 'styled-components';
function App() {
return <div style="{{" color:>Hello</div>;
}
const sheet = new ServerStyleSheet();
try {
const html = renderToString(sheet.collectStyles(<app></app>));
const styles = sheet.getStyleTags();
console.log(html);
console.log(styles);
} finally {
sheet.seal();
}
如何配置 Next.js 以支持 styled-components?
要在 Next.js 14 中正确支持 styled-components,需要在 `_document.tsx` 中集成 `ServerStyleSheet`,确保服务端生成的样式被注入到 HTML 的 `
` 标签中。这样客户端 hydration 时就能直接应用正确的样式,避免闪烁。

// pages/_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<app></app>),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
{initialProps.styles}
{sheet.getStyleElement()}
>
),
};
} finally {
sheet.seal();
}
}
render() {
return (
styled-components 在服务端渲染时的样式注入流程是怎样的?
styled-components 在服务端渲染时,通过 `ServerStyleSheet` 收集所有组件的样式,并将其转换为 CSS 字符串。这些样式随后被注入到 HTML 的 `
` 标签中,确保客户端 hydration 时能立即应用正确的样式。这一过程避免了样式闪烁,提升了用户体验。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











