کتابخانههای CSS-in-JS به شما اجازه میدهند استایلها را مستقیماً درون کامپوننتهای React تعریف کنید. در Next.js، استفاده از این کتابخانهها در ترکیب با Server Components و Streaming نیازمند پشتیبانی از رندرینگ همزمان React 18 است.
در دایرکتوری app، کتابخانههای زیر در Client Components پشتیبانی میشوند:
کتابخانه emotion در حال توسعهٔ پشتیبانی است.
پیکربندی شامل سه مرحله است:
useServerInsertedHTML برای تزریق استایلها قبل از محتوا// app/registry.tsx
'use client'
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
export default function StyledJsxRegistry({ children }) {
const [jsxStyleRegistry] = useState(() => createStyleRegistry())
useServerInsertedHTML(() => {
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return <>{styles}</>
})
return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}// app/layout.tsx
import StyledJsxRegistry from './registry'
export default function RootLayout({ children }) {
return (
<html>
<body>
<StyledJsxRegistry>{children}</StyledJsxRegistry>
</body>
</html>
)
}// next.config.js
module.exports = {
compiler: {
styledComponents: true,
},
}// 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 }) {
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>
)
}// app/layout.tsx
import StyledComponentsRegistry from './lib/registry'
export default function RootLayout({ children }) {
return (
<html>
<body>
<StyledComponentsRegistry>{children}</StyledComponentsRegistry>
</body>
</html>
)
}<head> تزریق میشوندکتابخانههای CSS-in-JS در Next.js امکان تعریف استایلهای پویا و قابل مدیریت را فراهم میکنند. با پیکربندی صحیح رجیستری و استفاده از هوک useServerInsertedHTML، میتوان از این کتابخانهها در ترکیب با Server Components و Streaming بهرهبرداری کرد.