英文:
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
问题
- 这是否意味着我必须在每个使用StyledComponents的组件中使用
use-client
指令? - 如果是这样,是否可以在一个文件中编写所有的StyledComponents,使用
use-client
指令置于顶部,然后根据需要将这些Client Components导入Server Components? - 上述方法是否会将Server Components转变为Client Components?
- 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
- Does that mean I have to use the
use-client
directive in every component that uses StyledComponents? - 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? - Will the approach above somehow turn the Server Components into Client Components?
- The Next.js docs state that all components within the
app
directory are Server Components by default. If we save a component outside theapp
directory and import it into a Server Component in theapp
directory, will that imported function then also become a Server Component?
答案1
得分: 6
- 你每次使用 StyledComponents 时都必须使用它。
- 可以,但是 Next.js 会将它渲染为客户端组件,即使你在服务器组件内导入它。
- 根据文档,如果你尝试渲染的页面中所有组件都带有'use client'指令,它将使该组件成为客户端组件。如果页面中有任何服务器组件,Next.js 将在服务器端渲染它们,并将其余部分发送到客户端。
- 是的,只要导入的组件没有使用'use client'指令,它就会变成服务器组件。
希望对你有所帮助。
英文:
I'll try my best to answer your questions.
- Yes you have to use it every time you use StyledComponents.
- It is possible but Next.js will render it as Client Component even though you import it inside a Server Component.
- 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.
- Yes it will become server components as long as the components that are imported isn't using the 'use client' directive.
Hope it helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论