我想在Next.13中通过服务器端渲染样式化组件,你好吗?

t40tm48m  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(171)

在特定时间样式化之前呈现组件
我想在服务器端呈现样式化的组件

rmbxnbpk

rmbxnbpk1#

文档中的答案:https://nextjs.org/docs/app/building-your-application/styling/css-in-js#styled-components
使用以下代码创建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

import StyledComponentsRegistry from './lib/registry';
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <StyledComponentsRegistry>{children}</StyledComponentsRegistry>
      </body>
    </html>
  );
}

相关问题