Skip to content

Chakra UI 参考

适用范围:Chakra UI v3.x(2026 年 5 月最新 v3.35.0)。本页是 API 速查手册——具体用法参见 指南

包速查

包名用途必装
@chakra-ui/react100+ 核心组件 + style props + system API
@emotion/reactCSS-in-JS 底层 (Emotion)
@chakra-ui/cliCLI 工具 (snippet add 命令)npx 即可
@ark-ui/reactHeadless 底层组件库 (可选直接用)一般不需要
next-themes暗色模式集成 (v3 默认)跟随 snippet
react-icons推荐图标库(替代 v2 @chakra-ui/icons推荐
lucide-react推荐图标库(替代方案)推荐
react-hook-form表单库(推荐)推荐
zodSchema 校验(推荐)推荐

核心 install 命令

bash
pnpm add @chakra-ui/react @emotion/react
npx @chakra-ui/cli snippet add        # 生成 Provider / Toaster / ColorMode

@chakra-ui/react - 100+ 组件清单

Layout(17)

组件说明
Box通用容器(Style Props 入口)
Flex弹性盒
Grid / GridItemCSS Grid 网格
Stack通用排列(含 Stack.Separator)
HStack横向 Stack 简写
VStack纵向 Stack 简写
Container限宽容器
Center居中容器
AbsoluteCenter绝对定位居中
AspectRatio固定宽高比
Bleed超出父容器的负边距
Float浮动定位
Group紧密分组
ScrollArea自定义滚动条容器
Separator分割线(v3 替代 v2 Divider)
SimpleGrid响应式简单网格
Splitter可拖拽分割面板
Wrap自动换行的横向布局
SpacerFlex 弹性填充

Typography(14)

组件说明
Headingh1-h6 标题
Text通用文本
Blockquote引用块
Code行内代码
CodeBlock代码块(含语法高亮)
Em强调文本
Highlight高亮关键词
Kbd键盘按键
Link链接
LinkOverlay整个区域可点击的链接遮罩
List列表(ListRoot / ListItem)
Mark标记
Proseprose 容器
RichTextEditor富文本编辑器

Forms(22)

组件说明
Field字段包装(v3 替代 FormControl)
Fieldset字段组
Input / InputGroup / InputAddon / InputElement单行文本 + 前后附加
Textarea多行文本
NumberInput数字输入
PasswordInput密码输入
PinInputPIN 码输入
Checkbox单选框
CheckboxCard卡片样式 Checkbox
Radio / RadioGroup单选
RadioCard卡片样式 Radio
Switch开关
Slider / RangeSlider滑块
Select自定义下拉(基于 Ark UI)
NativeSelect原生 select(v3 替代 v2 Select)
Combobox自动补全 + 多选下拉
TagsInput标签输入
Editable行内可编辑文本
ColorPicker颜色选择器
ColorSwatch颜色色块
FileUpload文件上传
SegmentedControl分段控件

Data Display(13)

组件说明
Avatar (Root / Image / Fallback / Badge)头像
Badge徽章
Card (Root / Header / Body / Footer)卡片
Clipboard剪贴板复制
Image图片
DataList键值对列表
Icon图标容器
Marquee跑马灯
QRCode二维码
Stat统计数字
Table (Root / Header / Body / Row / Cell / ColumnHeader)表格
Tag标签
Timeline时间线

Feedback(8)

组件说明
Alert (Root / Indicator / Title / Description)警告提示
EmptyState空状态
Progress (Root / Track / Range / ValueText)进度条
ProgressCircle环形进度(v3 替代 CircularProgress)
Skeleton / SkeletonText / SkeletonCircle骨架屏
Spinner加载指示器
Status状态指示器
Toast / ToasterToast 通知系统

Disclosure(7)

组件说明
Accordion (Root / Item / ItemTrigger / ItemContent / ItemBody / ItemIndicator)手风琴
Breadcrumb (Root / List / Item / Link / Separator / CurrentLink)面包屑
Carousel轮播
Collapsible (Root / Trigger / Content)折叠
Pagination (Root / PrevTrigger / NextTrigger / Items)分页
Steps (Root / List / Item / Indicator / Title / Separator / Content)步骤条
Tabs (Root / List / Trigger / Content / Indicator)选项卡

Overlays(9)

组件说明
ActionBar动作栏(底部固定操作条)
Dialog (Root / Trigger / Backdrop / Positioner / Content / Header / Title / Body / Footer / CloseTrigger)对话框(v3 替代 v2 Modal)
Drawer (同 Dialog 结构)抽屉
HoverCard悬停卡片
Menu (Root / Trigger / Positioner / Content / Item / ItemGroup / Separator)菜单
OverlayManager遮罩管理
Popover (Root / Trigger / Positioner / Content / Arrow / Header / Body / CloseTrigger)弹出框
ToggleTip点击式 Tooltip
Tooltip (snippet)工具提示

Buttons(4)

组件说明
Button / ButtonGroup标准按钮
CloseButton关闭按钮
IconButton图标按钮
DownloadTrigger下载触发器

Date & Time(2)

组件说明
Calendar日历
DatePicker日期选择器

Utilities(13)

组件说明
ClientOnly仅客户端渲染
EnvironmentProvider环境上下文
For迭代渲染(替代 .map)
LocaleProvider国际化上下文
FormatNumber数字格式化
FormatByte字节格式化
Presence过渡动画容器
Portal传送门
Show条件渲染
SkipNav跳过导航(a11y)
VisuallyHidden视觉隐藏
Theme主题局部覆盖
Checkmark / Radiomark通用 check / radio 标记

Style Props 完整表

Margin(10)

PropCSS 属性
mmargin
mtmargin-top
mbmargin-bottom
mlmargin-left
mrmargin-right
mxmargin-inline (left+right)
mymargin-block (top+bottom)
marginInlinemargin-inline (RTL aware)
marginBlockmargin-block
marginInlineStart / marginInlineEndlogical margin

Padding(10)

PropCSS 属性
ppadding
ptpadding-top
pbpadding-bottom
plpadding-left
prpadding-right
pxpadding-inline
pypadding-block
paddingInlinepadding-inline
paddingBlockpadding-block
paddingInlineStart / paddingInlineEndlogical padding

Sizing(8)

PropCSS 属性
w / widthwidth
h / heightheight
minW / minWidthmin-width
maxW / maxWidthmax-width
minH / minHeightmin-height
maxH / maxHeightmax-height
boxSizewidth + height 同值

Color(5)

PropCSS 属性
colorcolor
bg / backgroundbackground
backgroundColorbackground-color
borderColorborder-color
colorPalette主题色板(影响所有 color/bg/border)

Typography(16)

PropCSS 属性
fontSizefont-size
fontWeightfont-weight
fontFamilyfont-family
lineHeightline-height
letterSpacingletter-spacing
textAligntext-align
textTransformtext-transform
textDecorationtext-decoration
fontStylefont-style
whiteSpacewhite-space
wordBreakword-break
textOverflowtext-overflow
overflowWrapoverflow-wrap
verticalAlignvertical-align
lineClamp-webkit-line-clamp (多行截断)
truncate单行截断 (overflow+ellipsis+nowrap)

Background(5)

PropCSS 属性
bgImagebackground-image
bgSizebackground-size
bgPositionbackground-position
bgRepeatbackground-repeat
bgGradientlinear-gradient 等

Border(13)

PropCSS 属性
borderborder 缩写
borderWidthborder-width
borderStyleborder-style
borderColorborder-color
borderRadiusborder-radius
borderTop / borderBottom / borderLeft / borderRight单边 border
borderTopWidth / borderTopColor / borderTopStyle单边 width/color/style
borderTopLeftRadius / borderTopRightRadius单角圆角

Shadow(2)

PropCSS 属性
boxShadowbox-shadow
textShadowtext-shadow

Layout(10)

PropCSS 属性
displaydisplay
flexflex 缩写
flexDirectionflex-direction
flexWrapflex-wrap
flexBasisflex-basis
flexGrowflex-grow
flexShrinkflex-shrink
gapgap
rowGaprow-gap
columnGapcolumn-gap
alignItemsalign-items
justifyContentjustify-content
alignSelfalign-self
justifySelfjustify-self
orderorder

Grid(10)

PropCSS 属性
gridTemplateColumnsgrid-template-columns
gridTemplateRowsgrid-template-rows
gridTemplateAreasgrid-template-areas
gridColumngrid-column
gridRowgrid-row
gridColumnGapgrid-column-gap
gridRowGapgrid-row-gap
gridGapgrid-gap
gridAreagrid-area
gridAutoFlowgrid-auto-flow

Position(8)

PropCSS 属性
pos / positionposition
toptop
leftleft
rightright
bottombottom
zIndexz-index
insetinset (top+left+right+bottom)
insetInline / insetBlocklogical inset

Visibility(4)

PropCSS 属性
opacityopacity
visibilityvisibility
hideFrom在某断点及以上隐藏(v3 替代 v2 Hide above)
hideBelow在某断点以下隐藏

Overflow(3)

PropCSS 属性
overflowoverflow
overflowXoverflow-x
overflowYoverflow-y

Transform(7)

PropCSS 属性
transformtransform
transformOrigintransform-origin
rotaterotate (CSS)
scalescale (CSS)
scaleX / scaleYscale single axis
translateX / translateYtranslate single axis
skew / skewX / skewYskew

Transition(4)

PropCSS 属性
transitiontransition
transitionPropertytransition-property
transitionDurationtransition-duration
transitionTimingFunctiontransition-timing-function

Filter(5)

PropCSS 属性
filterfilter
backdropFilterbackdrop-filter
blurfilter: blur()
brightnessfilter: brightness()
contrastfilter: contrast()

Interactivity(4)

PropCSS 属性
cursorcursor
pointerEventspointer-events
userSelectuser-select
outlineoutline

Animation(2)

PropCSS 属性
animationanimation
animationNameanimation-name

Conditional Style Props 完整表

Pseudo Classes(30+)

条件选择器
_hover:hover
_active:active
_focus:focus
_focusWithin:focus-within
_focusVisible:focus-visible
_disabled:disabled / [aria-disabled=true]
_checked:checked / [aria-checked=true]
_visited:visited
_selected[aria-selected=true] / [data-selected]
_expanded[aria-expanded=true]
_required:required
_invalid[aria-invalid=true] / [data-invalid]
_valid:valid
_readOnly:read-only
_empty:empty
_first:first-child
_last:last-child
_odd:nth-child(odd)
_even:nth-child(even)
_indeterminate:indeterminate
_currentPage[aria-current=page] (v3 替代 _activeLink)
_currentStep[aria-current=step] (v3 替代 _activeStep)

Pseudo Elements(8)

条件选择器
_before::before
_after::after
_placeholder::placeholder
_file::file-selector-button
_firstLetter::first-letter
_firstLine::first-line
_marker::marker
_selection::selection

Group / Peer(10)

条件说明
_groupHover父 group hover 时
_groupFocus父 group focus 时
_groupActive父 group active 时
_groupDisabled父 group disabled 时
_groupChecked父 group checked 时
_peerHover兄弟 peer hover 时
_peerFocus兄弟 peer focus 时
_peerActive兄弟 peer active 时
_peerDisabled兄弟 peer disabled 时
_peerChecked兄弟 peer checked 时

Media Queries(11)

条件说明
_dark暗色模式 ([data-theme=dark].dark)
_light浅色模式
_osDarkOS 暗色偏好
_osLightOS 浅色偏好 (v3 替代 v2 _mediaDark)
_highContrast高对比度偏好
_lessContrast低对比度偏好
_motionReduce减少动画偏好
_motionSafe允许动画
_portrait竖屏
_landscape横屏
_print打印
_rtlRTL 方向
_ltrLTR 方向

Responsive Breakpoints(6 + 高级)

断点像素 / em
base0px+
sm30em / 480px+
md48em / 768px+
lg62em / 992px+
xl80em / 1280px+
2xl96em / 1536px+

高级断点目标

写法说明
mdToXlmd ≤ 视口 < xl
lgOnly仅 lg 断点
smDown< sm
mdUp≥ md
mdDown< md
xlUp≥ xl

createSystem + defineConfig 完整选项

ts
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react";

const config = defineConfig({
  // ─── 全局配置 ───────────────────────────────
  preflight: true,                       // 启用 CSS 重置
  cssVarsRoot: ":where(html)",           // CSS 变量根选择器
  cssVarsPrefix: "chakra",               // CSS 变量前缀
  strictTokens: false,                   // 严格 token 模式

  // ─── 全局样式 ───────────────────────────────
  globalCss: {
    "html, body": {
      fontFamily: "body",
      bg: "bg",
      color: "fg",
    },
  },

  // ─── 主题配置 ───────────────────────────────
  theme: {
    breakpoints: {
      base: "0em",
      sm: "30em",
      md: "48em",
      lg: "62em",
      xl: "80em",
      "2xl": "96em",
    },

    // ─── Base Tokens(design values)────────
    tokens: {
      colors: { /* 详见下文 Token 体系 */ },
      spacing: { /* ... */ },
      sizes: { /* ... */ },
      radii: { /* ... */ },
      shadows: { /* ... */ },
      fontSizes: { /* ... */ },
      fontWeights: { /* ... */ },
      lineHeights: { /* ... */ },
      letterSpacings: { /* ... */ },
      fonts: { /* ... */ },
      zIndices: { /* ... */ },
      borders: { /* ... */ },
      animations: { /* ... */ },
      cursor: { /* ... */ },
      easings: { /* ... */ },
      durations: { /* ... */ },
    },

    // ─── Semantic Tokens(语义化)──────────
    semanticTokens: {
      colors: {
        danger: { value: "{colors.red.500}" },
        primary: {
          value: { base: "{colors.brand.500}", _dark: "{colors.brand.400}" },
        },
      },
    },

    // ─── Recipes(组件变体)────────────────
    recipes: {
      button: defineRecipe({ /* ... */ }),
    },

    // ─── Slot Recipes(多部分组件)─────────
    slotRecipes: {
      card: defineSlotRecipe({ /* ... */ }),
    },

    // ─── Keyframes(动画)──────────────────
    keyframes: {
      spin: {
        from: { transform: "rotate(0deg)" },
        to: { transform: "rotate(360deg)" },
      },
    },

    // ─── Text Styles(预设文本样式)────────
    textStyles: {
      heading: {
        value: {
          fontFamily: "heading",
          fontWeight: "bold",
          lineHeight: "shorter",
        },
      },
    },

    // ─── Layer Styles(预设层样式)─────────
    layerStyles: {
      card: {
        value: {
          bg: "bg.panel",
          borderRadius: "lg",
          boxShadow: "md",
        },
      },
    },
  },

  // ─── 自定义条件 ─────────────────────────────
  conditions: {
    cqSm: "@container(min-width: 320px)",
    child: "& > *",
  },
});

export const system = createSystem(defaultConfig, config);

defineRecipe API

ts
import { defineRecipe } from "@chakra-ui/react";

export const buttonRecipe = defineRecipe({
  className: "chakra-button",   // 生成的 class 前缀

  base: {
    display: "inline-flex",
    alignItems: "center",
    fontWeight: "medium",
  },

  variants: {
    variant: {
      solid: { bg: "colorPalette.500", color: "white" },
      outline: { borderWidth: "1px" },
      ghost: { bg: "transparent" },
    },
    size: {
      sm: { px: "3", py: "1", fontSize: "sm" },
      md: { px: "4", py: "2", fontSize: "md" },
      lg: { px: "6", py: "3", fontSize: "lg" },
    },
  },

  compoundVariants: [
    {
      variant: "outline",
      size: "lg",
      css: { borderWidth: "2px" },
    },
  ],

  defaultVariants: {
    variant: "solid",
    size: "md",
  },
});

defineSlotRecipe API

ts
import { defineSlotRecipe } from "@chakra-ui/react";

export const cardRecipe = defineSlotRecipe({
  className: "chakra-card",
  slots: ["root", "header", "body", "footer"],

  base: {
    root: { bg: "bg.panel", borderRadius: "lg" },
    header: { p: "4" },
    body: { p: "4" },
    footer: { p: "4" },
  },

  variants: {
    size: {
      sm: { header: { p: "3" }, body: { p: "3" } },
      lg: { header: { p: "6" }, body: { p: "6" } },
    },
  },

  defaultVariants: { size: "md" },
});

ChakraProvider 完整选项

tsx
import { ChakraProvider } from "@chakra-ui/react";

<ChakraProvider
  value={system}                  // createSystem 生成的实例
>
  {children}
</ChakraProvider>;

v3 只有 value prop(与 v2 的 theme prop 区别)。

ColorModeProvider(next-themes)选项

tsx
import { ColorModeProvider } from "@/components/ui/color-mode";

<ColorModeProvider
  attribute="class"                       // class 或 data-theme
  defaultTheme="system"                   // system / light / dark
  enableSystem={true}                     // 启用系统跟随
  disableTransitionOnChange={true}        // 切换时禁用过渡
  forcedTheme={undefined}                 // 强制特定 theme(不可切换)
  themes={["light", "dark"]}              // 可选 theme 列表
  storageKey="theme"                      // localStorage key
>
  {children}
</ColorModeProvider>;

useColorMode

ts
const {
  colorMode,         // "light" | "dark"
  setColorMode,      // (mode: "light" | "dark" | "system") => void
  toggleColorMode,   // () => void  light <-> dark
} = useColorMode();

useColorModeValue

ts
const value = useColorModeValue(lightValue, darkValue);

useBreakpoint / useBreakpointValue

ts
import { useBreakpoint, useBreakpointValue } from "@chakra-ui/react";

// 当前断点
const bp = useBreakpoint();
// 返回 "base" | "sm" | "md" | "lg" | "xl" | "2xl"

// 根据断点取值
const value = useBreakpointValue({
  base: "mobile",
  md: "desktop",
});

Toast API

createToaster 选项

ts
import { createToaster } from "@chakra-ui/react";

export const toaster = createToaster({
  placement: "top-end",          // 6 个位置
  pauseOnPageIdle: true,
  max: 5,                         // 最多同时显示数
  duration: 5000,                 // 默认显示时长
  overlap: false,
  offsets: { top: "0px", bottom: "0px", left: "0px", right: "0px" },
});

placement 可选:

  • top-start / top / top-end
  • bottom-start / bottom / bottom-end

toaster.create

ts
toaster.create({
  id: "unique-id",
  title: "标题",
  description: "描述",
  type: "success",           // success / error / warning / info / loading
  duration: 5000,
  closable: true,
  action: {
    label: "撤销",
    onClick: () => {},
  },
});

toaster.update / dismiss / promise

ts
toaster.update("id", { title: "新标题" });
toaster.dismiss("id");
toaster.dismiss();           // 全部关闭

toaster.promise(promise, {
  loading: { title: "加载中" },
  success: { title: "成功" },
  error: { title: "失败" },
});

Token 体系

Spacing Scale(默认)

Token
00
0.50.125rem (2px)
10.25rem (4px)
1.50.375rem (6px)
20.5rem (8px)
2.50.625rem (10px)
30.75rem (12px)
3.50.875rem (14px)
41rem (16px)
51.25rem (20px)
61.5rem (24px)
71.75rem (28px)
82rem (32px)
92.25rem (36px)
102.5rem (40px)
123rem (48px)
143.5rem (56px)
164rem (64px)
205rem (80px)
246rem (96px)
328rem (128px)
4010rem (160px)
4812rem (192px)
5614rem (224px)
6416rem (256px)
7218rem (288px)
8020rem (320px)
9624rem (384px)

Sizes Scale

同 spacing + 额外别名:

Token
3xs14rem (224px)
2xs16rem (256px)
xs20rem (320px)
sm24rem (384px)
md28rem (448px)
lg32rem (512px)
xl36rem (576px)
2xl42rem (672px)
3xl48rem (768px)
4xl56rem (896px)
5xl64rem (1024px)
6xl72rem (1152px)
7xl80rem (1280px)
8xl90rem (1440px)
full100%
minmin-content
maxmax-content
fitfit-content
prose65ch

Color Palette(默认 10 色 × 11 shade)

v3 起每色板 11 shade(50-950):

css
--colors-{color}-50 ~ --colors-{color}-950

默认色板(10 色):

色名用途
gray中性灰(默认 colorPalette)
red红色
orange橙色
yellow黄色
green绿色
teal蓝绿
blue蓝色
cyan青色
purple紫色
pink粉色

每色 11 shade:50 / 100 / 200 / 300 / 400 / 500 / 600 / 700 / 800 / 900 / 950

Font Size Scale

Token
xs0.75rem
sm0.875rem
md1rem
lg1.125rem
xl1.25rem
2xl1.5rem
3xl1.875rem
4xl2.25rem
5xl3rem
6xl3.75rem
7xl4.5rem
8xl6rem
9xl8rem

Font Weight

Token
hairline100
thin200
light300
normal400
medium500
semibold600
bold700
extrabold800
black900

Line Height

Token
none1
shorter1.25
short1.375
base1.5
tall1.625
taller2
loose2

Letter Spacing

Token
tighter-0.05em
tight-0.025em
normal0
wide0.025em
wider0.05em
widest0.1em

Border Radius

Token
none0
xs0.125rem
sm0.25rem
md0.375rem
lg0.5rem
xl0.75rem
2xl1rem
3xl1.5rem
full9999px

Box Shadow

Token
xs0 0 0 1px rgba(0,0,0,0.05)
sm0 1px 2px 0 rgba(0,0,0,0.05)
md0 4px 6px -1px rgba(0,0,0,0.1)
lg0 10px 15px -3px rgba(0,0,0,0.1)
xl0 20px 25px -5px rgba(0,0,0,0.1)
2xl0 25px 50px -12px rgba(0,0,0,0.25)
innerinset 0 2px 4px 0 rgba(0,0,0,0.06)
outline0 0 0 3px rgba(66,153,225,0.6)
nonenone

Z-Index

Token
hide-1
autoauto
base0
docked10
dropdown1000
sticky1100
banner1200
overlay1300
modal1400
popover1500
skipLink1600
toast1700
tooltip1800

Semantic Tokens(默认提供)

v3 默认提供以下语义 token(自适应暗色 / 浅色):

Background

Token用途
bg默认背景
bg.subtle弱化背景
bg.muted静音背景
bg.emphasized强调背景
bg.inverted反转背景
bg.panel面板背景(卡片等)
bg.error错误背景
bg.warning警告背景
bg.success成功背景
bg.info信息背景

Foreground

Token用途
fg默认文本色
fg.subtle弱化文本
fg.muted静音文本
fg.error错误文本
fg.warning警告文本
fg.success成功文本
fg.info信息文本
fg.inverted反转文本

Border

Token用途
border默认边框
border.subtle弱化边框
border.muted静音边框
border.error错误边框
border.warning警告边框
border.success成功边框
border.info信息边框

Snippet CLI 命令

bash
# 安装所有默认 snippet
npx @chakra-ui/cli snippet add

# 安装特定 snippet
npx @chakra-ui/cli snippet add color-mode
npx @chakra-ui/cli snippet add toaster
npx @chakra-ui/cli snippet add tooltip
npx @chakra-ui/cli snippet add dialog
npx @chakra-ui/cli snippet add drawer

# 列出可用的 snippet
npx @chakra-ui/cli snippet ls

# 自动迁移(v2 → v3)
npx @chakra-ui/codemod upgrade

TypeScript 核心类型

ts
import type {
  // 主题
  SystemContext,
  Tokens,
  SemanticTokens,
  RecipeConfig,
  SlotRecipeConfig,
  RecipeVariantProps,
  SlotRecipeVariantProps,

  // 组件 props
  BoxProps,
  ButtonProps,
  TextProps,
  HeadingProps,
  StackProps,
  FlexProps,
  ContainerProps,
  InputProps,
  TextareaProps,
  SelectProps,
  CheckboxProps,
  RadioProps,
  SwitchProps,
  DialogProps,
  DrawerProps,
  MenuProps,
  TooltipProps,

  // Style Props
  SystemStyleObject,
  StyleProps,
  ConditionalValue,
  ResponsiveValue,

  // Color Palette
  ColorPalette,

  // 系统
  ChakraProviderProps,
} from "@chakra-ui/react";

主题类型扩展

ts
// src/chakra.d.ts
import "@chakra-ui/react";

declare module "@chakra-ui/react" {
  interface ConfigTokenMap {
    colors: {
      brand: { 50: string; 100: string; /* ... */ 950: string };
    };
  }
}

Ark UI 底层组件清单

如果需要直接用 headless 组件、可以从 @ark-ui/react 引入:

bash
pnpm add @ark-ui/react

Ark UI 提供 50+ headless 组件

  • Accordion / AlertDialog / Avatar / Carousel / Checkbox / Clipboard / Collapsible / Combobox / DatePicker / Dialog / Editable / FileUpload / Float / Hoverable / Listbox / Menu / NumberInput / Pagination / PinInput / Popover / Presence / Progress / QrCode / RadioGroup / RatingGroup / SegmentControl / Select / Signal / Slider / Splitter / Stepper / Steps / Switch / Tabs / Tags / TagsInput / Toast / Toggle / ToggleGroup / Tooltip / Tour / TreeView / Vimeo / YouTube

详见 ark-ui.com

升级路径

v2 → v3 重大变更

安装依赖

  • 移除 @emotion/styledframer-motion peer deps
  • 加入 npx @chakra-ui/cli snippet add 步骤
  • 移除 @chakra-ui/icons → 用 react-icons / lucide-react
  • 移除 @chakra-ui/hooks → 用 react-use / usehooks-ts

Provider

  • <ChakraProvider theme={theme}><ChakraProvider value={system}>
  • 新增 snippet 提供的 <Provider> 封装
  • ColorModeProvider 改用 next-themes
  • ColorModeScript 完全移除

主题配置

  • extendTheme()createSystem(defaultConfig, defineConfig(...))
  • token 值必须 { value: "..." } 包装
  • 色板每色 11 shade(新增 950)
  • 新增 semanticTokens + recipes + slotRecipes + conditions

API 重命名

  • colorSchemecolorPalette
  • isOpenopen
  • isDisableddisabled
  • isInvalidinvalid
  • isRequiredrequired
  • defaultIsOpendefaultOpen
  • isLoadingloading
  • noOfLineslineClamp
  • truncatedtruncate
  • spacinggap(Stack/VStack/HStack)

组件重构

  • ModalDialog.Root + Backdrop + Positioner + Content + ...
  • FormControlField.Root + Label + HelperText + ErrorText
  • AvatarAvatar.Root + Image + Fallback + Badge
  • BreadcrumbBreadcrumb.Root + List + Item + Link
  • AccordionAccordion.Root + Item + ItemTrigger + ItemContent + ItemBody
  • CardCard.Root + Header + Body + Footer
  • TabsTabs.Root + List + Trigger + Content
  • AlertAlert.Root + Indicator + Title + Description
  • SelectNativeSelect.Root + Field + Indicator

移除组件

  • StackItem → 用 Box
  • FocusLock → 装 react-focus-lock
  • AlertDialog → 用 Dialog + role="alertdialog"
  • CircularProgress → 改名 ProgressCircle
  • StackDivider → 用 Stack.Separator
  • Show / Hide → 用 hideFrom / hideBelow props
  • Collapse → 改名 Collapsible
  • Divider → 改名 Separator
  • Fade / Slide 等过渡 → 统一 Presence

自动迁移

bash
npx @chakra-ui/codemod upgrade

关键模板项目

bash
# Chakra UI v3 + Next.js App Router(推荐)
pnpm create next-app my-app --typescript --app
cd my-app
pnpm add @chakra-ui/react @emotion/react
npx @chakra-ui/cli snippet add

# Chakra UI v3 + Vite + React + TypeScript
pnpm create vite my-app -- --template react-ts
cd my-app
pnpm add @chakra-ui/react @emotion/react
pnpm add -D vite-tsconfig-paths
npx @chakra-ui/cli snippet add

# Playground
# https://chakra-ui.com/docs/get-started/playground

官方资源

资源URL
主文档https://chakra-ui.com/
入门https://chakra-ui.com/docs/get-started/installation
Migration v2 → v3https://chakra-ui.com/docs/get-started/migration
组件总览https://chakra-ui.com/docs/components/concepts/overview
Theminghttps://chakra-ui.com/docs/theming/overview
Recipeshttps://chakra-ui.com/docs/theming/recipes
Slot Recipeshttps://chakra-ui.com/docs/theming/slot-recipes
Dark Modehttps://chakra-ui.com/docs/styling/dark-mode
Conditional Styleshttps://chakra-ui.com/docs/styling/conditional-styles
Responsive Designhttps://chakra-ui.com/docs/styling/responsive-design
CLIhttps://chakra-ui.com/docs/get-started/cli
Playgroundhttps://chakra-ui.com/docs/get-started/playground
Changeloghttps://chakra-ui.com/docs/get-started/changelog
Figmahttps://chakra-ui.com/docs/get-started/figma
GitHubhttps://github.com/chakra-ui/chakra-ui
Ark UI(headless)https://ark-ui.com
Panda CSS(引擎)https://panda-css.com
Zag.js(状态机)https://zagjs.com

社区扩展生态

用途
@chakra-ui/cliCLI 工具
react-icons推荐图标库(替代 v2 @chakra-ui/icons
lucide-react替代图标库
react-hook-form表单库(与 Field 完美配合)
@hookform/resolversRHF + Zod / Yup 集成
zodSchema 校验(推荐)
next-themes暗色模式(v3 默认)
react-focus-lock焦点陷阱(v3 移除 FocusLock 替代品)
@tanstack/react-table数据表格(Chakra Table 不够强时)
@tabler/icons-reactTabler 图标库