Skip to Content
文档

仅限客户端

仅用于在客户端渲染内容。

Source

用法

¥Usage

import { ClientOnly, Skeleton } from "@chakra-ui/react"
<ClientOnly>
  <ColorModeButton />
</ClientOnly>

示例

¥Examples

回退

¥Fallback

在客户端内容准备就绪时,使用 fallback 属性渲染加载状态。

¥Use the fallback prop to render a loading state while the client-side content is being prepared.

<ClientOnly fallback={<Skeleton boxSize="8" />}>
  <ColorModeButton />
</ClientOnly>

渲染属性(推荐)

¥Render Prop (Recommended)

当你的组件访问仅限浏览器的 API(例如 windowdocumentlocalStorage)时,请使用渲染属性模式来防止服务器端渲染问题:

¥When your component accesses browser-only APIs (like window, document, or localStorage), use the render prop pattern to prevent server-side rendering issues:

<ClientOnly fallback={<Skeleton />}>
  {() => (
    <div>
      Current URL: {window.location.href}
      Screen width: {window.innerWidth}px
    </div>
  )}
</ClientOnly>

此模式确保访问浏览器 API 的组件仅在客户端进行评估,从而防止混合不匹配和服务器端错误。

¥This pattern ensures that components accessing browser APIs are only evaluated on the client side, preventing hydration mismatches and server-side errors.

它还可以用于渲染服务器端不需要的重型组件。

直接子组件(谨慎使用)

¥Direct Children (Use with Caution)

虽然你可以将组件直接作为子组件传递,但请谨慎处理访问浏览器 API 的组件:

¥While you can pass components directly as children, be careful with components that access browser APIs:

/* ❌ This may cause server-side errors */
<ClientOnly fallback={<Skeleton />}>
  <ComponentThatUsesWindow />
</ClientOnly>

/* ✅ This is safe */
<ClientOnly fallback={<Skeleton />}>
  {() => <ComponentThatUsesWindow />}
</ClientOnly>

属性

¥Props

这些属性可以传递给 ClientOnly 组件。

¥These props can be passed to the ClientOnly component.

PropDefaultType
fallback
string | number | bigint | boolean | ReactElement<unknown, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | Promise<...>

The fallback content to render while the component is mounting on the client side.

as
React.ElementType

The underlying element to render.

asChild
boolean

Use the provided child element as the default rendered element, combining their props and behavior.

For more details, read our Composition guide.

Previous

复选标记

Next

EnvironmentProvider