在特定时间样式化之前呈现组件我想在服务器端呈现样式化的组件
rmbxnbpk1#
文档中的答案:https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components使用以下代码创建lib/registry.tsx
lib/registry.tsx
'use client'; import React, { useState } from 'react'; import { useServerInsertedHTML } from 'next/navigation'; import { ServerStyleSheet, StyleSheetManager } from 'styled-components'; export default function StyledComponentsRegistry({ children, }: { children: React.ReactNode; }) { // Only create stylesheet once with lazy initial state // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet()); useServerInsertedHTML(() => { const styles = styledComponentsStyleSheet.getStyleElement(); styledComponentsStyleSheet.instance.clearTag(); return <>{styles}</>; }); if (typeof window !== 'undefined') return <>{children}</>; return ( <StyleSheetManager sheet={styledComponentsStyleSheet.instance}> {children} </StyleSheetManager> ); }
并在全局布局中 Package 子对象(app/layout.tsx)
app/layout.tsx
import StyledComponentsRegistry from './lib/registry'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html> <body> <StyledComponentsRegistry>{children}</StyledComponentsRegistry> </body> </html> ); }
1条答案
按热度按时间rmbxnbpk1#
文档中的答案:https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components
使用以下代码创建
lib/registry.tsx
并在全局布局中 Package 子对象(
app/layout.tsx
)