样式化组件CSS未在NextJS 13中应用

yruzcnhs  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(108)

我在项目中使用NextJs(版本13.4.10)和styled-components(版本6.0.4)。当我第一次运行这个项目(npm run dev)时,所有的样式都被应用了,但是如果我修改了代码并重新渲染它,样式就不再起作用了。
这里有我的代码:

"use client";
import React from "react";
import Image from "next/image";
import { BannerWrapper, ImageBannerWrapper, BannerTitle } from "./style";

export default function Banner() {
  return (
    <>
      <ImageBannerWrapper className="absolute flex">
        <Image
          src="/images/banner/Mask-banner.png"
          height={709}
          width={747}
          alt="banner"
        />
        <BannerTitle className="font-primary text-9xl text-white text-left font-normal">
          <span className="font-primary text-9xl text-white text-left font-semibold">
            Let us guide you to the best choice.
          </span>
        </BannerTitle>
      </ImageBannerWrapper>
      <BannerWrapper className="flex items-center bg-default -mt-16" />
    </>
  );
}

字符串

pbossiut

pbossiut1#

我在documentation of NextJs中找到了问题的答案。
由于我使用的是stylled-component,我应该将CSS-in-JS配置为三步:

  • 样式注册表,用于收集呈现中的所有CSS规则。
  • 新的useServerInsertedHTML钩子在任何可能使用规则的内容之前注入规则。
  • 在初始服务器端呈现期间使用样式注册表 Package 应用的客户端组件。
    新建注册表:
'use client' 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
 
export default function StyledJsxRegistry({
  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 [jsxStyleRegistry] = useState(() => createStyleRegistry())
 
  useServerInsertedHTML(() => {
    const styles = jsxStyleRegistry.styles()
    jsxStyleRegistry.flush()
    return <>{styles}</>
  })
 
  return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>
}

字符串

然后用注册表 Package 你的root布局:

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

相关问题