Skip to Content
文档

颜色模式

添加对亮色和暗色模式的支持

Chakra UI 依赖 next-themes 来添加对明暗颜色模式的支持。

¥Chakra UI relies on next-themes to add support for light and dark color mode.

设置

¥Setup

在大多数情况下,你已通过 CLI 在 Provider 组件中安装并设置了它。如果没有,你可以手动安装。

¥In most cases, you have it installed and set up by the CLI in the Provider component. If not, you can install it manually.

npx @chakra-ui/cli snippet add color-mode

该代码片段包含一些钩子和组件,使其感觉类似于 Chakra v2。

¥The snippet includes hooks and components that make it feel similar to Chakra v2.

import {
  ColorModeButton,
  DarkMode,
  LightMode,
  useColorMode,
  useColorModeValue,
} from "@/components/ui/color-mode"

useColorMode

useColorMode 钩子返回当前颜色模式以及一个用于切换颜色模式的函数。

¥The useColorMode hook returns the current color mode and a function to toggle the color mode.

在应用树中的任何位置调用 toggleColorModesetColorMode 可在颜色模式之间切换。

¥Calling toggleColorMode or setColorMode anywhere in your app tree toggles the color mode from light or dark and vice versa.

useColorModeValue

useColorModeValue 钩子根据当前颜色模式返回一个值。

¥The useColorModeValue hook returns a value based on the current color mode.

签名:

¥Here's the signature:

const result = useColorModeValue("<light-mode-value>", "<dark-mode-value>")

如果颜色模式为 light,则返回值为亮模式的值;如果颜色模式为 dark,则返回值为夜间模式的值。

¥The value returned will be the value of the light mode if the color mode is light, and the value of the dark mode if the color mode is dark.

This box's style will change based on the color mode.

水合不匹配

¥Hydration Mismatch

在服务器端渲染 (SSR) 中使用 useColorModeValueuseColorMode 时,你可能会注意到页面加载时出现水合不匹配的情况。这是因为颜色模式值是在服务器端计算的。

¥When using useColorModeValue or useColorMode in SSR, you may notice a hydration mismatch when the page is mounted. This is because the color mode value is computed on the server side.

为了避免这种情况,请使用 ClientOnly 组件封装使用 useColorModeValue 的组件,并渲染一个骨架,直到挂载到客户端。

¥To avoid this, use the ClientOnly component to wrap the component that uses useColorModeValue and render a skeleton until mounted on the client side.

ColorModeButton

颜色模式代码段内置 ColorModeButton 组件,你可以导入它来渲染一个用于切换颜色模式的图标按钮。

¥The color mode snippet comes with the ColorModeButton component built-in, you can import it to render an icon button that toggles the color mode.

它会在服务器端渲染骨架,在客户端渲染图标。

¥It renders a skeleton on the server side and the icon on the client side.

强制彩色模式

¥Forced Color Mode

颜色模式代码段内置 LightModeDarkMode 组件,你可以导入它来强制启用颜色模式。

¥The color mode snippet comes with the LightMode and DarkMode components built-in, you can import it to force the color mode.

你可能需要更新 color-mode.tsx 代码片段,因为最近添加了 LightModeDarkMode 组件。

Previous

动画

Next

服务器组件