Skip to Content
文档

虚拟颜色

创建颜色占位符以实现更好的主题和自定义。

概述

¥Overview

Chakra 允许你在项目中创建虚拟颜色或颜色占位符。colorPalette 属性用于创建虚拟颜色。

¥Chakra allows you to create a virtual color or color placeholder in your project. The colorPalette property is how you create virtual color.

<Box
  colorPalette="blue"
  bg={{ base: "colorPalette.100", _hover: "colorPalette.200" }}
>
  Hello World
</Box>

这将在鼠标悬停时转换为 blue.100blue.200 的背景颜色。

¥This will translate to the blue.100 background color and blue.200 background color on hover.

用法

¥Usage

虚拟颜色的基本要求是颜色必须具有一致的命名约定。默认情况下,Chakra 对我们提供的每种颜色使用 50-950 个颜色值。

¥The fundamental requirement for virtual colors is that your colors must have a consistent naming convention. By default, Chakra use 50-950 color values for each color we provide.

这使你更容易创建和使用虚拟颜色。假设我们需要从头开始创建一个可主题化的轮廓按钮。

¥This makes it easier for you to create and use virtual colors. Let's say we need to create a themable outline button from scratch.

<chakra.button
  borderWidth="1px"
  colorPalette="red"
  borderColor="colorPalette.500"
  _hover={{
    borderColor: "colorPalette.600",
  }}
>
  Click me
</chakra.button>

秘诀

¥Recipes

虚拟颜色在与配方一起使用时最有用。

¥Virtual colors are most useful when used with recipes.

const buttonRecipe = defineRecipe({
  base: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    // set the color palette
    colorPalette: "blue",
  },
  variants: {
    variant: {
      primary: {
        bg: "colorPalette.500",
        color: "white",
      },
      outline: {
        borderWidth: "1px",
        borderColor: "colorPalette.500",
        _hover: {
          borderColor: "colorPalette.600",
        },
      },
    },
  },
})

组件

¥Components

Chakra 中的大多数内置组件都支持虚拟颜色。

¥Most built-in components in Chakra support virtual colors.

<Button colorPalette="blue">Click me</Button>
<Button colorPalette="red" variant="outline">
  Click me
</Button>

夜间模式

¥Dark mode

虚拟颜色的另一个神奇之处在于,你可以将它们与暗黑模式结合使用。

¥Another amazing thing you can do with virtual colors is to use them with dark mode.

<Box
  colorPalette="blue"
  bg={{ base: "colorPalette.600", _dark: "colorPalette.400" }}
>
  Hello World
</Box>

此元素在亮模式下将具有 blue.600 背景颜色,在夜间模式下将具有 blue.400 背景颜色。

Previous

条件样式

Next

层叠图层