> Leaf UI 0.6.0 · Package: @ifhover/leaf-ui · Source: b30c3d3a8fa9c5e15d0d0522cebfbd33f60c6b06
> Browser documentation: https://ifhover.github.io/leaf-ui/v/0.6.0/components/config-provider.html

> For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/v/0.6.0/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/v/0.6.0/llms-full.txt.

# ConfigProvider 配置

为整个应用或局部区域统一设置主题、语言和组件默认参数。

放在应用入口时作用于整个应用；嵌套使用时只调整当前区域。

| 想调整什么        | 使用的配置                   |
| ------------ | ----------------------- |
| 内置文本与自定义语言   | `locale`、`translations` |
| 主题色、外观、尺寸与间距 | `theme`、`density`       |
| 统一组件参数       | `components`            |

## 多语言

`locale` 切换日期面板、空状态、清除按钮等内置文本。业务标题、字段标签和选项内容由应用自行翻译。

### 内置语言

以下语言已内置，无需额外导入语言包。未配置 `locale` 时，默认使用简体中文。

| 语言      | `locale` |
| ------- | -------- |
| 简体中文    | `zh-CN`  |
| 繁體中文    | `zh-TW`  |
| English | `en-US`  |
| 日本語     | `ja-JP`  |
| 한국어     | `ko-KR`  |

其他语言需要[提供翻译资源](#补充自己的语言)。仅传入其他语言代码不会自动翻译内置文本；未找到的词条最终回退到英文。

### 切换语言

更新 `locale` 即可切换语言。在下拉框中选择语言，再打开日期或空选项控件，可比较五种语言的内置提示。


日期

空选项

locale.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/locale.tsx"
import { ConfigProvider, DatePicker, Form, FormField, Select, Space } from '@ifhover/leaf-ui';

import { useState } from 'react';

export function ConfigProviderLocale() {
  const [locale, setLocale] = useState('zh-CN');
  return (
    <Space direction="vertical" align="stretch">
      <Select
        aria-label="组件语言"
        value={locale}
        onChange={setLocale}
        options={[
          { value: 'zh-CN', label: '简体中文' },
          { value: 'zh-TW', label: '繁體中文' },
          { value: 'en-US', label: 'English' },
          { value: 'ja-JP', label: '日本語' },
          { value: 'ko-KR', label: '한국어' },
        ]}
      />
      <ConfigProvider locale={locale}>
        <Form>
          <FormField label="日期">
            <DatePicker />
          </FormField>
          <FormField label="空选项">
            <Select options={[]} />
          </FormField>
        </Form>
      </ConfigProvider>
    </Space>
  );
}
```

展开代码

嵌套区域未指定语言时继承上层；`direction` 调整文字方向，`weekStartsOn` 设置一周的起始日，浮层也会继承这些配置。

### 补充自己的语言

复制[完整英文 JSON
](/leaf-ui/v/0.6.0/locales/en-US.json)作为模板，翻译后导入并传给 `translations`
。键是语言代码，JSON 只包含按组件分组的文本，不需要重复写语言代码。可以只提供部分词条。
👽 下面用[火星文](https://zh.wikipedia.org/wiki/火星文)演示自定义资源，作为一个小彩蛋。它是一种混用谐音字、形近字和符号的网络写法。

未翻译的词条回退英文。字段名称、确认框正文等业务内容仍由应用提供。

火星文使用私用语言标记 `zh-CN-x-mars`，日期和数字仍按简体中文的区域格式显示。它仅用于演示，不属于内置语言。


日期

空选项

共 24 條數據123

打开确认框

translations.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/translations.tsx"
import { Button, ConfigProvider, DatePicker, Form, FormField, Pagination, Select, Space, useConfirm } from '@ifhover/leaf-ui';

import mars from './zh-CN-x-mars.json';

const translations = { 'zh-CN-x-mars': mars };

function Controls() {
  const { confirm } = useConfirm();
  return (
    <Space direction="vertical" align="stretch">
      <Form>
        <FormField label="日期">
          <DatePicker />
        </FormField>
        <FormField label="空选项">
          <Select options={[]} />
        </FormField>
      </Form>
      <Pagination total={24} showTotal />
      <Button
        variant="outline"
        onClick={() =>
          void confirm({
            title: '继续操作？',
            children: '确认与取消按钮使用火星文，未翻译的文本回退英文。',
          })
        }
      >
        打开确认框
      </Button>
    </Space>
  );
}

export function ConfigProviderTranslations() {
  return (
    <ConfigProvider locale={['zh-CN-x-mars', 'en-US']} translations={translations}>
      <Controls />
    </ConfigProvider>
  );
}
```

展开代码

示例中的 `zh-CN-x-mars.json`：

```json file="../../src/examples/config-provider/zh-CN-x-mars.json"
{
  "common": {
    "confirm": "確萣",
    "cancel": "筭ㄋ"
  },
  "select": {
    "placeholder": "挑①個唄",
    "empty": "暫蒔木洧選項"
  },
  "datePicker": {
    "placeholder": "選個ㄖ剘"
  },
  "pagination": {
    "total": "共 {total} 條數據"
  }
}

```

`locale={['zh-CN-x-mars', 'en-US']}` 按顺序查找每个缺失词条，最后由内置英文兜底。第一项始终控制当前语言、日期与数字的区域格式；字符串等价于单项数组，空数组无效。不会自动添加 `zh-CN-x-mars → zh-CN` 或 `fr-CA → fr` 等回退。

嵌套时 `translations` 按语言和词条合并；未传 `locale` 则继承，显式传入则替换整条语言链。组件实例与 `components` 设置的文案优先。完整规则、类型、JSON Schema 和词条检查见[翻译资源](https://ifhover.github.io/leaf-ui/v/0.6.0/api/translations.md)。

## 主题与外观

### 区域主题

主题会应用到区域内的组件和浮层。通常只需要修改主题色或基础圆角，其余样式会随之调整。


项目名称

项目类型

保存设置

basic.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/basic.tsx"
import { Button, ConfigProvider, Form, FormField, Input, Select } from '@ifhover/leaf-ui';

export function ConfigProviderBasic() {
  return (
    <ConfigProvider theme={{ primaryColor: '#7654c6', borderRadius: 8 }}>
      <Form onSubmit={(event) => event.preventDefault()}>
        <FormField label="项目名称">
          <Input defaultValue="Leaf UI" />
        </FormField>
        <FormField label="项目类型">
          <Select
            defaultValue="website"
            options={[
              { value: 'website', label: '网站' },
              { value: 'app', label: '应用' },
            ]}
          />
        </FormField>
        <Button type="submit">保存设置</Button>
      </Form>
    </ConfigProvider>
  );
}
```

展开代码

### 区域密度

`density="compact"` 适合信息较多的界面，会一起收紧控件和内容间距；默认使用 `comfortable`。嵌套区域可单独设置。


舒适

项目名称

负责人

重置

紧凑

项目名称

负责人

重置

density.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/density.tsx"
import { Button, ConfigProvider, Form, FormField, Input, Select, Space, Text } from '@ifhover/leaf-ui';

export function ConfigProviderDensity() {
  return (
    <Space direction="vertical" align="stretch" size="lg">
      {(['comfortable', 'compact'] as const).map((density) => (
        <ConfigProvider key={density} density={density}>
          <Space direction="vertical" align="stretch">
            <Text tone="muted">{density === 'compact' ? '紧凑' : '舒适'}</Text>
            <Form>
              <FormField label="项目名称">
                <Input defaultValue="Leaf UI" />
              </FormField>
              <FormField label="负责人">
                <Select
                  options={[
                    { value: 'lin', label: 'Lin' },
                    { value: 'alex', label: 'Alex' },
                  ]}
                  defaultValue="lin"
                />
              </FormField>
              <Button type="reset" variant="outline">
                重置
              </Button>
            </Form>
          </Space>
        </ConfigProvider>
      ))}
    </Space>
  );
}
```

展开代码

### 基础高度

需要改变整体尺寸基准时，设置 `theme.controlHeight`，小、大尺寸会自动派生。无需逐项调整按钮和输入框的高度。


基础高度：36px

小尺寸按钮

默认尺寸按钮

大尺寸按钮

sizes.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/sizes.tsx"
import { Button, ConfigProvider, Form, FormField, Slider, Space, Text } from '@ifhover/leaf-ui';

import { useState } from 'react';

export function ConfigProviderSizes() {
  const [height, setHeight] = useState(36);
  return (
    <Space direction="vertical" align="stretch" size="lg">
      <Form>
        <FormField label={`基础高度：${height}px`}>
          <Slider min={28} max={44} value={height} onChange={setHeight} showValue={false} />
        </FormField>
      </Form>
      <ConfigProvider theme={{ controlHeight: height }}>
        <Space wrap align="end" size="lg">
          {(
            [
              ['sm', '小尺寸'],
              ['md', '默认尺寸'],
              ['lg', '大尺寸'],
            ] as const
          ).map(([size, label]) => (
            <Space key={size} direction="vertical" size="sm">
              <Text tone="muted">{label}</Text>
              <Button size={size} variant="outline">
                按钮
              </Button>
            </Space>
          ))}
        </Space>
      </ConfigProvider>
    </Space>
  );
}
```

展开代码

进一步定制见[定制主题](https://ifhover.github.io/leaf-ui/v/0.6.0/guide/theming.md)。`theme.components` 调整组件局部样式，下方的 `components` 设置组件默认参数；两者用途不同，可以同时使用。服务端接入见 [服务端渲染](https://ifhover.github.io/leaf-ui/v/0.6.0/guide/ssr.md)。

## 组件默认值

**常用参数设一次，省去每个组件重复传参。** 用 `components` 统一按钮样式、输入提示、弹窗关闭方式，后续调整也只改一处。

放在应用入口作用于全站，放在局部只影响当前区域；个别组件仍可用自身参数覆盖。

### 统一表单习惯

下面统一输入提示、清除按钮和按钮样式，结束日期与保存按钮单独覆盖。


项目名称

开始日期

结束日期

重置保存（实例覆盖）

defaults.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/defaults.tsx"
import { Button, ConfigProvider, DatePicker, Form, FormField, Input, Space } from '@ifhover/leaf-ui';

export function ConfigProviderDefaults() {
  return (
    <ConfigProvider
      components={{
        Button: { variant: 'outline' },
        Input: { placeholder: '请输入项目名称', allowClear: true },
        DatePicker: { placeholder: '选择项目开始日期', allowClear: true },
      }}
    >
      <Form onSubmit={(event) => event.preventDefault()}>
        <FormField label="项目名称">
          <Input />
        </FormField>
        <FormField label="开始日期">
          <DatePicker />
        </FormField>
        <FormField label="结束日期">
          <DatePicker placeholder="实例覆盖：选择结束日期" />
        </FormField>
        <Space wrap>
          <Button type="reset">重置</Button>
          <Button type="submit" variant="solid">
            保存（实例覆盖）
          </Button>
        </Space>
      </Form>
    </ConfigProvider>
  );
}
```

展开代码

### 防止误点遮罩关闭弹窗

编辑时不希望误点遮罩就关掉弹窗，可以统一设置 `Modal: { maskClosable: false }`。区域内的 Modal 都会沿用，无需逐个设置；关闭按钮和 Esc 仍然可用。


打开弹窗

modal-defaults.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/modal-defaults.tsx"
import { Button, ConfigProvider, Modal, Paragraph } from '@ifhover/leaf-ui';

import { useState } from 'react';

export function ConfigProviderModalDefaults() {
  const [open, setOpen] = useState(false);

  return (
    <ConfigProvider components={{ Modal: { maskClosable: false } }}>
      <Button onClick={() => setOpen(true)}>打开弹窗</Button>
      <Modal open={open} title="点击遮罩不会关闭" onClose={() => setOpen(false)}>
        <Paragraph>
          试着点击弹窗外的遮罩，弹窗会保持打开。仍可通过关闭按钮、底部操作或 Esc 关闭。
        </Paragraph>
      </Modal>
    </ConfigProvider>
  );
}
```

展开代码

### 继承与覆盖

统一默认值后，局部仍可灵活调整：**实例参数 > 内层配置 > 外层配置 > 组件内置值**。


外层配置小尺寸 · 边框

内层覆盖尺寸大尺寸 · 继承边框

实例覆盖参数默认尺寸 · 主要

inheritance.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/inheritance.tsx"
import { Button, ConfigProvider, Flex, Space, Text } from '@ifhover/leaf-ui';

export function ConfigProviderInheritance() {
  return (
    <ConfigProvider components={{ Button: { variant: 'outline', size: 'sm' } }}>
      <Space direction="vertical" align="stretch">
        <Flex justify="space-between" align="center" gap="md">
          <Text tone="muted">外层配置</Text>
          <Button>小尺寸 · 边框</Button>
        </Flex>
        <ConfigProvider components={{ Button: { size: 'lg' } }}>
          <Space direction="vertical" align="stretch">
            <Flex justify="space-between" align="center" gap="md">
              <Text tone="muted">内层覆盖尺寸</Text>
              <Button>大尺寸 · 继承边框</Button>
            </Flex>
            <Flex justify="space-between" align="center" gap="md">
              <Text tone="muted">实例覆盖参数</Text>
              <Button size="md" variant="solid">
                默认尺寸 · 主要
              </Button>
            </Flex>
          </Space>
        </ConfigProvider>
      </Space>
    </ConfigProvider>
  );
}
```

展开代码

### 清除继承

将组件配置设为 `null`，可在局部恢复它的内置默认值，例如 `components={{ Input: null }}`。


继承默认参数

清除当前区域的默认参数

reset.tsx

复制代码

```tsx lineNumbers file="../../src/examples/config-provider/reset.tsx"
import { ConfigProvider, Form, FormField, Input, type LeafComponentDefaults } from '@ifhover/leaf-ui';

const defaults = { Input: { readOnly: true } } satisfies LeafComponentDefaults;

export function ConfigProviderReset() {
  return (
    <ConfigProvider components={defaults}>
      <Form>
        <FormField label="继承默认参数">
          <Input defaultValue="此输入框为只读" />
        </FormField>
        <ConfigProvider components={{ Input: null }}>
          <FormField label="清除当前区域的默认参数">
            <Input defaultValue="试试修改这里的内容" />
          </FormField>
        </ConfigProvider>
      </Form>
    </ConfigProvider>
  );
}
```

展开代码


配置键、合并规则与使用建议

使用 `LeafComponentDefaults` 获得类型提示，可配参数见[完整参考](https://ifhover.github.io/leaf-ui/v/0.6.0/api/component-defaults.md#leafcomponentdefaults)。
- 键名与组件名一致，如 `Input`、`Modal`。组合组件 `Table.Cell` 写作 `TableCell`，`Table.Root` 写作 `Table`；别名 `FAB`、`ResizablePanels` 使用 `FloatButton`、`Splitter`。
- 只有 `undefined` 会回退到默认值；`false`、`0`、空字符串和类型允许的 `null` 均保留。对象、数组、类名和回调整体替换。
- 组件配置为 `null` 时清除继承，空对象和 `undefined` 继续继承；其他组件与主题不受影响。
- 每个实例的数据和事件仍写在组件上，如 `Select.options`、`Modal.open`、`onChange`。
- 更新配置时传入新对象，不要直接修改原对象。
- 内部按钮通过所属组件的参数调整，例如 `Modal.confirmButtonProps`；不会跟随全局 `Button` 配置。

## API

### ConfigProvider API

| 属性                  | 类型                                                                                                                               | 默认值             | 说明                                                        |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------------------------------------------- |
| `locale`            | `LeafLocale \| readonly LeafLocale[]`                                                                                            | `'zh-CN'`       | 当前语言与逐词条回退顺序；未指定则继承                                       |
| `translations`      | `Readonly<Record<string, `[`LeafTranslation`](https://ifhover.github.io/leaf-ui/v/0.6.0/api/translations.md#leaftranslation)`>>` | —               | 按语言代码提供 JSON 翻译，嵌套时按词条合并                                  |
| `theme`             | [`LeafTheme`](#leaftheme)                                                                                                        | —               | 区域主题；未设置的字段继承上层                                           |
| `direction`         | `'ltr' \| 'rtl'`                                                                                                                 | —               | 文字和交互方向。                                                  |
| `weekStartsOn`      | `0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6`                                                                                                | —               | 一周起始日，0 表示周日、1 表示周一。                                      |
| `getPopupContainer` | `() => Element \| DocumentFragment`                                                                                              | —               | 返回浮层的挂载容器，也可返回 ShadowRoot。                                |
| `maskBlur`          | `boolean`                                                                                                                        | `true`          | 启用 Modal、Drawer 及基于 Modal 的确认框、命令面板等遮罩模糊；关闭可减少渲染开销，嵌套时继承。 |
| `density`           | `'comfortable' \| 'compact'`                                                                                                     | `'comfortable'` | 继承控件、表单、菜单、列表与浮层的密度；显式尺寸优先于预设。                            |
| `components`        | [`LeafComponentDefaults`](https://ifhover.github.io/leaf-ui/v/0.6.0/api/component-defaults.md#leafcomponentdefaults)             | —               | 当前区域的组件默认参数，嵌套时按组件和参数继承。                                  |

其余原生 div 属性、`className` 和 `style` 作用于区域容器。`maskBlur={false}` 关闭背景模糊，仍保留半透明遮罩；此设置独立于 `theme.motion`。

### LeafTheme

常用主题配置。未设置的字段继承外层区域。

| 属性              | 类型                                                                                                                             | 默认值         | 说明                                             |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------- | ---------------------------------------------- |
| `primaryColor`  | `string`                                                                                                                       | `'#20834a'` | 主题色，悬停和按下等状态自动生成；深色默认采用较浅的绿色                   |
| `borderRadius`  | `number \| string`                                                                                                             | `10`        | 基础圆角；数字为 px，小 / 中 / 大圆角按 0.6 / 1.2 / 1.6 倍生成   |
| `controlHeight` | `number \| string`                                                                                                             | `36`        | 基础控件高度；小 / 大尺寸分别减 / 加 6px                      |
| `fontSize`      | `number \| string`                                                                                                             | `14`        | 基础字号；小字号减 1px，大字号加 2px                         |
| `fontFamily`    | `string`                                                                                                                       | 系统无衬线字体     | 字体族                                            |
| `appearance`    | `'light' \| 'dark'`                                                                                                            | `'light'`   | 浅色或深色；嵌套时继承显式配置                                |
| `motion`        | `boolean`                                                                                                                      | `true`      | 启用当前区域的交互动效；系统减少动态效果优先，浮层继承此设置。                |
| `tokens`        | [`LeafThemeTokens`](https://ifhover.github.io/leaf-ui/v/0.6.0/api/theme-tokens.md#leafthemetokens)                             | —           | 可选的高级覆盖，不必配置全部字段                               |
| `spacing`       | `number`                                                                                                                       | —           | 基础间距，其他间距按比例派生。                                |
| `lineHeight`    | `number`                                                                                                                       | —           | 正文行高。                                          |
| `headingWeight` | `number`                                                                                                                       | —           | Typography 文档标题的字重；组件标题使用 `tokens.fontWeight`。 |
| `elevation`     | `'none' \| 'soft' \| 'medium'`                                                                                                 | —           | 整体阴影强度。                                        |
| `breakpoints`   | `Partial<Record<'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl', number>>`                                                                | —           | useBreakpoint 使用的响应式断点。                        |
| `components`    | `Record<string, `[`LeafComponentTokens`](https://ifhover.github.io/leaf-ui/v/0.6.0/api/theme-tokens.md#leafcomponenttokens)`>` | —           | 按组件名称覆盖局部样式。                                   |

### 类型与完整参考

组装可复用配置时，可按需导入类型：

```ts
import type { ConfigProviderProps, LeafComponentDefaults, LeafTheme } from '@ifhover/leaf-ui';
```

- [LeafComponentDefaults](https://ifhover.github.io/leaf-ui/v/0.6.0/api/component-defaults.md#leafcomponentdefaults)：组件名称与可配置的默认参数。
- [LeafThemeTokens](https://ifhover.github.io/leaf-ui/v/0.6.0/api/theme-tokens.md#leafthemetokens)：高级主题覆盖。
