如何在Next.js 13应用程序文件夹中使用StyledComponents?

huangapple go评论59阅读模式
英文:

How do I use StyledComponents in the Next.js 13 app folder?

问题

来自Next.js文档

> 警告:需要运行时JavaScript的CSS-in-JS库目前不支持Server Components。
>
> 下面的库在应用程序目录中的Client Components中受支持:
>
> - styled-jsx
> - styled-components
> - style9

问题

  1. 这是否意味着我必须在每个使用StyledComponents的组件中使用use-client指令?
  2. 如果是这样,是否可以在一个文件中编写所有的StyledComponents,使用use-client指令置于顶部,然后根据需要将这些Client Components导入Server Components?
  3. 上述方法是否会将Server Components转变为Client Components?
  4. Next.js文档说明app目录中的所有组件默认都是Server Components。如果我们将一个组件保存在app目录之外并将其导入app目录中的Server Component,那么导入的函数是否也会成为Server Component?
英文:

From the Next.js docs:

> Warning: CSS-in-JS libraries which require runtime JavaScript are not
> currently supported in Server Components.
>
> The following libraries are supported in Client Components in the app
> directory:
>
> - styled-jsx
> - styled-components
> - style9

Questions

  1. Does that mean I have to use the use-client directive in every component that uses StyledComponents?
  2. If so, is it possible to write all StyledComponents in one file, with the use-client directive at top, and then just import these Client Components as needed into the Server Components?
  3. Will the approach above somehow turn the Server Components into Client Components?
  4. The Next.js docs state that all components within the app directory are Server Components by default. If we save a component outside the app directory and import it into a Server Component in the app directory, will that imported function then also become a Server Component?

答案1

得分: 6

  1. 你每次使用 StyledComponents 时都必须使用它。
  2. 可以,但是 Next.js 会将它渲染为客户端组件,即使你在服务器组件内导入它。
  3. 根据文档,如果你尝试渲染的页面中所有组件都带有'use client'指令,它将使该组件成为客户端组件。如果页面中有任何服务器组件,Next.js 将在服务器端渲染它们,并将其余部分发送到客户端。
  4. 是的,只要导入的组件没有使用'use client'指令,它就会变成服务器组件。

希望对你有所帮助。

英文:

I'll try my best to answer your questions.

  1. Yes you have to use it every time you use StyledComponents.
  2. It is possible but Next.js will render it as Client Component even though you import it inside a Server Component.
  3. From the docs, it will make the component into Client Component if the page that you're trying to render are all components with 'use client' directive. Next.js will render it server side if there are any Server Component inside the page and send the rest to the client.
  4. Yes it will become server components as long as the components that are imported isn't using the 'use client' directive.

Hope it helps.

huangapple
  • 本文由 发表于 2023年2月16日 14:12:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定