服务器组件
了解如何将 Chakra UI 与 React 服务器组件结合使用。
React 服务器组件是 React 中的一项新功能,它允许你构建在服务器端渲染并将 UI 返回客户端而无需进行数据合并的组件。
¥React Server Components is a new feature in React that allows you to build components that render on the server and return UI to the client without hydration.
客户端组件仍然由服务器渲染,但在客户端上进行了数据同步。了解更多关于 服务器组件模式 的信息
¥Client components are still server-rendered but hydrated on the client. Learn more about Server component patterns
Chakra UI 组件是客户端组件,因为它们依赖于 useState
、useRef
和 useState
,而这些在服务器组件中不可用。
¥Chakra UI components are client components because they rely on useState
,
useRef
and useState
which are not available in server components.
TLDR
,Chakra UI 组件无需添加 'use client' 指令即可与 React 服务器组件一起使用。¥TLDR: By default, Chakra UI components can be used with React Server Components without adding the 'use client' directive.
用法
¥Usage
以下是如何在 Next.js 中将 Chakra UI 组件与 React 服务器组件结合使用的示例。
¥Here's an example of how to use Chakra UI components with React Server Components in Next.js
import { Heading } from "@chakra-ui/react"
import fs from "node:fs"
export default async function Page() {
const content = fs.readFileSync("path/to/file.md", "utf-8")
return <Heading as="h1">{content}</Heading>
}
Chakra 工厂
¥Chakra Factory
使用 chakra()
工厂函数时,请使用 use client
指令并将组件移动到专用文件。
¥When using the chakra()
factory function, use the use client
directive and
move the component to a dedicated file.
"use client"
import { chakra } from "@chakra-ui/react"
export const BlogPost = chakra("div", {
base: {
color: "red",
},
variants: {
primary: {
true: { color: "blue" },
false: { color: "green" },
},
},
})
然后在页面服务器组件中导入该组件
¥Then import the component in your page server component
import { BlogPost } from "./blog-post"
export default async function Page() {
const content = fs.readFileSync("path/to/file.md", "utf-8")
return <BlogPost>{content}</BlogPost>
}
钩子
¥Hooks
从 Chakra UI 导入钩子时,请使用 use client
指令。
¥When importing hooks from Chakra UI, use the use client
directive
"use client"
import { useBreakpointValue } from "@chakra-ui/react"
export function MyComponent() {
const value = useBreakpointValue({ base: "mobile", md: "desktop" })
return <div>{value}</div>
}
渲染属性
¥Render Props
使用渲染属性时,请使用 use client
指令。
¥When using render props, use the use client
directive
"use client"
import { ProgressContext } from "@chakra-ui/react"
export function MyComponent() {
return <ProgressContext>{({ value }) => <div>{value}</div>}</ProgressContext>
}