# Ant Design 组件文档
本文件包含所有组件文档的聚合内容。
> 总计 75 个组件
## _util-cn
Source: https://ant.design/components/_util-cn.md
---
category: Components
title: Util
subtitle: 工具类
description: 辅助开发,提供一些常用的工具方法。
showImport: false
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*rRDlT7ST8DUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*rRDlT7ST8DUAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 其他
order: 99
---
自 `5.13.0` 版本开始提供这些方法。
## GetRef
获取组件的 `ref` 属性定义,这对于未直接暴露或者子组件的 `ref` 属性定义非常有用。
```tsx
import { Select } from 'antd';
import type { GetRef } from 'antd';
type SelectRefType = GetRef; // BaseSelectRef
```
## GetProps
获取组件的 `props` 属性定义:
```tsx
import { Checkbox } from 'antd';
import type { GetProps } from 'antd';
type CheckboxGroupType = GetProps;
```
同时也支持获取 Context 的属性定义:
```tsx
import type { GetProps } from 'antd';
interface InternalContextProps {
name: string;
}
const Context = React.createContext({ name: 'Ant Design' });
type ContextType = GetProps; // InternalContextProps
```
### 与 `React.ComponentProps` 的区别 {#react-componentprops-diff}
`React.ComponentProps` 是 React 官方提供的通用工具类型,用于获取原生标签或 React 组件接受的 props,例如 `React.ComponentProps<'button'>` 或 `React.ComponentProps`,而 `GetProps` 则是 Ant Design 提供的补充类型:它不支持原生标签名,但除了 React 组件外,还可以直接获取 `React.Context` 的 value 类型,或者透传已经拿到的 props 类型对象。
## GetProp
获取组件的单个 `props` 或者 `context` 属性定义。它已经将 `NonNullable` 进行了封装,所以不用再考虑为空的情况:
```tsx
import { Select } from 'antd';
import type { GetProp, SelectProps } from 'antd';
// 以下两种都可以生效
type SelectOptionType1 = GetProp[number];
type SelectOptionType2 = GetProp[number];
type ContextOptionType = GetProp;
```
同时,支持通过第三个参数 `Return` 获取函数属性的返回值类型:
```tsx
import type { GetProp } from 'antd';
interface Props {
func?: (value: number) => string;
configOrFunc?: { configA?: string } | (() => { anotherB?: string });
}
type OnChangeReturn = GetProp; // string
type ClassNamesReturn = GetProp; // { anotherB?: string }
```
---
## affix-cn
Source: https://ant.design/components/affix-cn.md
---
category: Components
title: Affix
subtitle: 固钉
description: 将页面元素钉在可视范围。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YSm4RI3iOJ8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*03dxS64LxeQAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 其他
order: 7
---
## 何时使用 {#when-to-use}
当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。
页面可视范围过小时,慎用此功能以免出现遮挡页面内容的情况。
> 开发者注意事项:
>
> 自 `5.10.0` 起,由于 Affix 组件由 class 重构为 FC,之前获取 `ref` 并调用内部实例方法的写法都会失效。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Affix, Button } from 'antd';
const App: React.FC = () => {
const [top, setTop] = React.useState(100);
const [bottom, setBottom] = React.useState(100);
return (
<>
setTop(top + 10)}>
Affix top
setBottom(bottom + 10)}>
Affix bottom
>
);
};
export default App;
```
### 固定状态改变的回调
可以获得是否固定的状态。
```tsx
import React from 'react';
import { Affix, Button } from 'antd';
const App: React.FC = () => (
console.log(affixed)}>
120px to affix top
);
export default App;
```
### 滚动容器
用 `target` 设置 `Affix` 需要监听其滚动事件的元素,默认为 `window`。
```tsx
import React from 'react';
import { Affix, Button } from 'antd';
const containerStyle: React.CSSProperties = {
width: '100%',
height: 100,
overflow: 'auto',
boxShadow: '0 0 0 1px #1677ff',
scrollbarWidth: 'thin',
scrollbarGutter: 'stable',
};
const style: React.CSSProperties = {
width: '100%',
height: 1000,
};
const App: React.FC = () => {
const [container, setContainer] = React.useState(null);
return (
container}>
Fixed at the top of container
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| offsetBottom | 距离窗口底部达到指定偏移量后触发 | number | - | | × |
| offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | 0 | | × |
| target | 设置 `Affix` 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 | () => Window \| HTMLElement \| null | () => window | | × |
| onChange | 固定状态改变时触发的回调函数 | (affixed?: boolean) => void | - | | × |
**注意:**`Affix` 内的元素不要使用绝对定位,如需要绝对定位的效果,可以直接设置 `Affix` 为绝对定位:
```jsx
...
```
## FAQ
### Affix 使用 `target` 绑定容器时,元素会跑到容器外。 {#faq-target-container}
从性能角度考虑,我们只监听容器滚动事件。如果希望任意滚动,你可以在窗体添加滚动监听:
相关 issue:[#3938](https://github.com/ant-design/ant-design/issues/3938) [#5642](https://github.com/ant-design/ant-design/issues/5642) [#16120](https://github.com/ant-design/ant-design/issues/16120)
### Affix 在水平滚动容器中使用时, 元素 `left` 位置不正确。 {#faq-horizontal-scroll}
Affix 一般只适用于单向滚动的区域,只支持在垂直滚动容器中使用。如果希望在水平容器中使用,你可以考虑使用 原生 `position: sticky` 实现。
相关 issue: [#29108](https://github.com/ant-design/ant-design/issues/29108)
---
## alert-cn
Source: https://ant.design/components/alert-cn.md
---
category: Components
title: Alert
subtitle: 警告提示
description: 警告提示,展现需要关注的信息。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*QsvtS41m45UAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*gOTISoMFZV0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 反馈
order: 6
---
## 何时使用 {#when-to-use}
- 当某个页面需要向用户显示警告的信息时。
- 非浮层的静态展现形式,始终展现,不会自动消失,用户可以点击关闭。
## 代码演示 {#examples}
### 基本
最简单的用法,适用于简短的警告提示。
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 四种样式
共有四种样式 `success`、`info`、`warning`、`error`。
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 无边框
通过 `variant="filled"` 隐藏边框。
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 可关闭的警告提示
显示关闭按钮,点击可关闭警告提示。
```tsx
import React from 'react';
import { Alert } from 'antd';
const onClose: React.MouseEventHandler = (e) => {
console.log(e, 'I was closed.');
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### 含有辅助性文字介绍
含有辅助性文字介绍的警告提示。
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 图标
可口的图标让信息类型更加醒目。
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 顶部公告
页面顶部通告形式,默认有图标且 `type` 为 'warning'。
```tsx
import React from 'react';
import { Alert } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 轮播的公告
配合 [react-text-loop-next](https://npmjs.com/package/react-text-loop-next) 或 [react-fast-marquee](https://npmjs.com/package/react-fast-marquee) 实现消息轮播通知栏。
```tsx
import React from 'react';
import { Alert } from 'antd';
import Marquee from 'react-fast-marquee';
const App: React.FC = () => (
I can be a React component, multiple React components, or just some text.
}
/>
);
export default App;
```
### 平滑地卸载
平滑、自然的卸载提示。
```tsx
import React, { useState } from 'react';
import { Alert, Switch } from 'antd';
const App: React.FC = () => {
const [visible, setVisible] = useState(true);
const handleClose = () => {
setVisible(false);
};
return (
<>
{visible && (
)}
click the close button to see the effect
>
);
};
export default App;
```
### React 错误处理
友好的 [React 错误处理](https://zh-hans.react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) 包裹组件。
```tsx
import React, { useState } from 'react';
import { Alert, Button } from 'antd';
const { ErrorBoundary } = Alert;
const ThrowError: React.FC = () => {
const [error, setError] = useState();
const onClick = () => {
setError(new Error('An Uncaught Error'));
};
if (error) {
throw error;
}
return (
Click to throw an error
);
};
const App: React.FC = () => (
);
export default App;
```
### 操作
可以在右上角自定义操作项。
```tsx
import React from 'react';
import { Alert, Button, Flex } from 'antd';
const App: React.FC = () => (
<>
UNDO
}
closable
/>
Detail
}
/>
Done
}
closable
/>
Accept
Decline
}
closable
/>
>
);
export default App;
```
### 自定义标题对齐
未设置 `description` 时,Alert 会让图标、内容、操作区和关闭按钮作为整体垂直居中。组件库不默认改为 `flex-start` 布局并通过 token 补偿偏移,是因为当 `styles` 自定义字体、行高或操作区尺寸后,token 推导出的偏移量可能不再匹配实际样式。若标题可能换行,并希望这些元素与标题首行对齐,可以通过语义化 `styles` 自行调整。
```tsx
import React from 'react';
import { Alert, Button, Flex } from 'antd';
import type { AlertProps } from 'antd';
const wrapperStyle: React.CSSProperties = {
width: 360,
};
const title = 'Long alert title wraps to multiple lines when the alert container is narrow enough.';
const titleLineHeight = 22;
const iconSize = 14;
const closeIconSize = 12;
const smallButtonHeight = 24;
const firstLineStyles: AlertProps['styles'] = {
root: {
alignItems: 'flex-start',
},
icon: {
marginBlockStart: (titleLineHeight - iconSize) / 2,
},
actions: {
marginBlockStart: (titleLineHeight - smallButtonHeight) / 2,
},
close: {
marginBlockStart: (titleLineHeight - closeIconSize) / 2,
},
};
const App: React.FC = () => (
Action
}
/>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Alert 的 [语义化结构](#semantic-dom) 样式。
```tsx
import React from 'react';
import { Alert, Button, Flex } from 'antd';
import type { AlertProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
border-radius: 8px;
padding: 12px;
`,
}));
const styleFn: AlertProps['styles'] = ({
props: { type },
}): GetProp => {
if (type === 'success') {
return {
root: {
backgroundColor: 'rgba(82, 196, 26, 0.1)',
borderColor: '#b7eb8f',
},
icon: {
color: '#52c41a',
},
};
}
if (type === 'warning') {
return {
root: {
backgroundColor: 'rgba(250, 173, 20, 0.1)',
borderColor: '#ffe58f',
},
icon: {
color: '#faad14',
},
};
}
return {};
};
const App: React.FC = () => {
const alertSharedProps: AlertProps = {
showIcon: true,
classNames: {
root: classNames.root,
},
};
return (
Action}
/>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| action | 自定义操作项 | ReactNode | - | | × |
| ~~afterClose~~ | 关闭动画结束后触发的回调函数,请使用 `closable.afterClose` 替换 | () => void | - | | × |
| banner | 是否用作顶部公告 | boolean | false | | × |
| variant | 警告提示样式变体 | `outlined` \| `filled` | `outlined` | 6.4.0 | 6.4.0 |
| classNames | 自定义组件内部各语义化结构的类名。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| closable | 可关闭配置 | boolean \| [ClosableType](#closabletype) & React.AriaAttributes | `false` | | 5.15.0 |
| closeIcon | (仅支持全局配置)自定义关闭图标 | ReactNode | - | × | 5.14.0 |
| description | 警告提示的辅助性文字介绍 | ReactNode | - | | × |
| errorIcon | (仅支持全局配置)自定义错误图标 | ReactNode | - | × | 6.2.0 |
| icon | 自定义图标,`showIcon` 为 true 时有效 | ReactNode | - | | × |
| infoIcon | (仅支持全局配置)自定义信息图标 | ReactNode | - | × | 6.2.0 |
| ~~message~~ | 警告提示内容,请使用 `title` 替换 | ReactNode | - | | × |
| ~~onClose~~ | 关闭时触发的回调函数,请使用 `closable.onClose` 替换 | (e: MouseEvent) => void | - | | × |
| ~~closeIcon~~ | 自定义关闭图标,请使用 `closable.closeIcon` 替代 | ReactNode | - | - | × |
| ~~closeText~~ | 自定义关闭文案,请使用 `closable.closeIcon` 替代 | ReactNode | - | - | × |
| showIcon | 是否显示辅助图标 | boolean | false,`banner` 模式下默认值为 true | | × |
| styles | 自定义组件内部各语义化结构的内联样式。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| successIcon | (仅支持全局配置)自定义成功图标 | ReactNode | - | × | 6.2.0 |
| title | 警告提示内容 | ReactNode | - | | × |
| type | 指定警告提示的样式,有四种选择 `success`、`info`、`warning`、`error` | string | `info`,`banner` 模式下默认值为 `warning` | | × |
| warningIcon | (仅支持全局配置)自定义警告图标 | ReactNode | - | × | 6.2.0 |
### ClosableType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ---------- | ---------------------------- | ----------------------- | ------ | ---- |
| afterClose | 关闭动画结束后触发的回调函数 | function | - | - |
| closeIcon | 自定义关闭图标 | ReactNode | - | - |
| onClose | 关闭时触发的回调函数 | (e: MouseEvent) => void | - | - |
### Alert.ErrorBoundary
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| description | 自定义错误内容,如果未指定会展示报错堆栈 | ReactNode | {{ error stack }} | |
| ~~message~~ | 自定义错误标题,如果未指定会展示原生报错信息,请使用 `title` 替换 | ReactNode | {{ error }} | |
| title | 自定义错误标题,如果未指定会展示原生报错信息 | ReactNode | {{ error }} | |
## Semantic DOM
https://ant.design/components/alert-cn/semantic.md
## Design Token
## 组件 Token (Alert)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 组件圆角 | BorderRadius \| undefined | 8 |
| defaultPadding | 默认内间距 | Padding \| undefined | 8px 12px |
| withDescriptionIconSize | 带有描述时的图标尺寸 | string \| number | 24 |
| withDescriptionPadding | 带有描述的内间距 | Padding \| undefined | 20px 24px |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBorder | 错误色的描边色 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorInfo | 用于表示操作信息的 Token 序列,如 Alert 、Tag、 Progress 等组件都有用到该组梯度变量。 | string | |
| colorInfoBg | 信息色的浅色背景颜色。 | string | |
| colorInfoBorder | 信息色的描边色。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorSuccess | 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 | string | |
| colorSuccessBg | 成功色的浅色背景颜色,用于 Tag 和 Alert 的成功态背景色 | string | |
| colorSuccessBorder | 成功色的描边色,用于 Tag 和 Alert 的成功态描边色 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| colorWarningBg | 警戒色的浅色背景颜色 | string | |
| colorWarningBorder | 警戒色的描边色 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
---
## anchor-cn
Source: https://ant.design/components/anchor-cn.md
---
category: Components
title: Anchor
subtitle: 锚点
description: 用于跳转到页面指定位置。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ufP1TLS5VvIAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*_9_eTrgvHNQAAAAAAAAAAAAADrJ8AQ/original
demo:
group:
title: 导航
order: 3
---
## 何时使用 {#when-to-use}
需要展现当前页面上可供跳转的锚点链接,以及快速在锚点之间跳转。
> 开发者注意事项:
>
> 自 `4.24.0` 起,由于组件从 class 重构成 FC,之前一些获取 `ref` 并调用内部实例方法的写法都会失效
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Anchor, Col, Row } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 横向 Anchor
横向 Anchor。
```tsx
import React from 'react';
import { Anchor } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 静态位置
不浮动,状态不随页面滚动变化。
```tsx
import React from 'react';
import { Anchor } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义 onClick 事件
点击锚点不记录历史。
```tsx
import React from 'react';
import { Anchor } from 'antd';
const handleClick = (
e: React.MouseEvent,
link: {
title: React.ReactNode;
href: string;
},
) => {
e.preventDefault();
console.log(link);
};
const App: React.FC = () => (
);
export default App;
```
### 自定义锚点高亮
自定义锚点高亮。
```tsx
import React from 'react';
import { Anchor } from 'antd';
const getCurrentAnchor = () => '#anchor-demo-static';
const App: React.FC = () => (
);
export default App;
```
### 设置锚点滚动偏移量
锚点目标滚动到屏幕正中间。
```tsx
import React, { useEffect, useState } from 'react';
import { Anchor, Col, Row } from 'antd';
const style: React.CSSProperties = {
height: '30vh',
backgroundColor: 'rgba(0, 0, 0, 0.85)',
position: 'fixed',
top: 0,
insetInlineStart: 0,
width: '75%',
color: '#fff',
};
const App: React.FC = () => {
const topRef = React.useRef(null);
const [targetOffset, setTargetOffset] = useState();
useEffect(() => {
setTargetOffset(topRef.current?.clientHeight);
}, []);
return (
);
};
export default App;
```
### 监听锚点链接改变
监听锚点链接改变
```tsx
import React from 'react';
import { Anchor } from 'antd';
const onChange = (link: string) => {
console.log('Anchor:OnChange', link);
};
const App: React.FC = () => (
);
export default App;
```
### 替换历史中的 href
替换浏览器历史记录中的路径,后退按钮将返回到上一页而不是上一个锚点。
```tsx
import React from 'react';
import { Anchor, Col, Row } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Anchor 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Anchor, Col, Row } from 'antd';
import type { AnchorProps, GetProp } from 'antd';
const classNamesObject: AnchorProps['classNames'] = {
root: 'demo-anchor-root',
item: 'demo-anchor-item',
itemTitle: 'demo-anchor-title',
indicator: 'demo-anchor-indicator',
};
const stylesFn: AnchorProps['styles'] = (info): GetProp => {
if (info.props.direction === 'vertical') {
return {
root: {
backgroundColor: 'rgba(255,251,230,0.5)',
height: '100vh',
},
};
}
return {};
};
const items: NonNullable = [
{
key: 'part-1',
href: '#part-1',
title: 'Part 1',
},
{
key: 'part-2',
href: '#part-2',
title: 'Part 2',
},
{
key: 'part-3',
href: '#part-3',
title: 'Part 3',
},
];
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Anchor Props
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| affix | 固定模式 | boolean \| Omit | true | object: 5.19.0 | × |
| bounds | 锚点区域边界 | number | 5 | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| getContainer | 指定滚动的容器 | () => HTMLElement | () => window | | × |
| getCurrentAnchor | 自定义高亮的锚点 | (activeLink: string) => string | - | | × |
| offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | 0 | | × |
| showInkInFixed | `affix={false}` 时是否显示小方块 | boolean | false | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| targetOffset | 锚点滚动偏移量,默认与 offsetTop 相同,[例子](#anchor-demo-targetoffset) | number | - | | × |
| onChange | 监听锚点链接改变 | (currentActiveLink: string) => void | - | | × |
| onClick | `click` 事件的 handler | (e: MouseEvent, link: object) => void | - | | × |
| items | 数据化配置选项内容,支持通过 children 嵌套 | { key, href, title, target, children }\[] [具体见](#anchoritem) | - | 5.1.0 | × |
| direction | 设置导航方向 | `vertical` \| `horizontal` | `vertical` | 5.2.0 | × |
| replace | 替换浏览器历史记录中项目的 href 而不是推送它 | boolean | false | 5.7.0 | × |
### AnchorItem
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| key | 唯一标志 | string \| number | - | |
| href | 锚点链接 | string | - | |
| target | 该属性指定在何处显示链接的资源 | string | - | |
| title | 文字内容 | ReactNode | - | |
| children | 嵌套的 Anchor Link,`注意:水平方向该属性不支持` | [AnchorItem](#anchoritem)\[] | - | |
| replace | 替换浏览器历史记录中的项目 href 而不是推送它 | boolean | false | 5.7.0 |
| targetOffset | 设置单个锚点的滚动偏移量,会覆盖 Anchor 组件的 targetOffset 属性 | number | - | 6.4.0 |
### Link Props
建议使用 items 形式。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| href | 锚点链接 | string | - | |
| target | 该属性指定在何处显示链接的资源 | string | - | |
| title | 文字内容 | ReactNode | - | |
| targetOffset | 设置单个锚点的滚动偏移量,会覆盖 Anchor 组件的 targetOffset 属性 | number | - | 6.4.0 |
## Semantic DOM
https://ant.design/components/anchor-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Anchor)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| linkPaddingBlock | 链接纵向内间距 | number | 4 |
| linkPaddingInlineStart | 链接横向内间距 | number | 16 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| paddingXXS | 控制元素的极小内间距。 | number | |
## FAQ
### 在 `5.25.0+` 版本中,锚点跳转后,目标元素的 `:target` 伪类未按预期生效 {#faq-target-pseudo-class}
出于页面性能优化考虑,锚点跳转的实现方式从 `window.location.href` 调整为 `window.history.pushState/replaceState`。由于 `pushState/replaceState` 不会触发页面重载,因此浏览器不会自动更新 `:target` 伪类的匹配状态。可以手动构造完整URL:`href = window.location.origin + window.location.pathname + '#xxx'` 来解决这问题。
相关issues:[#53143](https://github.com/ant-design/ant-design/issues/53143) [#54255](https://github.com/ant-design/ant-design/issues/54255)
---
## app-cn
Source: https://ant.design/components/app-cn.md
---
category: Components
group: 其他
title: App
subtitle: 包裹组件
description: 提供重置样式和提供消费上下文的默认环境。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*HJz8SZos2wgAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*oC92TK44Ex8AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 提供可消费 React context 的 `message.xxx`、`Modal.xxx`、`notification.xxx` 的静态方法,可以简化 useMessage 等方法需要手动植入 `contextHolder` 的问题。
- 提供基于 `.ant-app` 的默认重置样式,解决原生元素没有 antd 规范样式的问题。
## 代码演示 {#examples}
### 基本用法
获取 `message`、`notification`、`modal` 实例。
```tsx
import React from 'react';
import { App, Button, Space } from 'antd';
// Sub page
const Page: React.FC = () => {
const { message, modal, notification } = App.useApp();
const showMessage = () => {
message.success('Success!');
};
const showModal = () => {
modal.warning({
title: 'This is a warning message',
content: 'some messages...some messages...',
});
};
const showNotification = () => {
notification.info({
title: 'Notification topLeft',
description: 'Hello, Ant Design!!',
placement: 'topLeft',
});
};
return (
Open message
Open modal
Open notification
);
};
// Entry component
export default () => (
);
```
### Hooks 配置
对 `message`、`notification` 进行配置。
```tsx
import React from 'react';
import { App, Button, Space } from 'antd';
// Sub page
const Page: React.FC = () => {
const { message, notification } = App.useApp();
const showMessage = () => {
message.success('Success!');
};
const showNotification = () => {
notification.info({
title: 'Notification',
description: 'Hello, Ant Design!!',
});
};
return (
Message for only one
Notification for bottomLeft
);
};
// Entry component
export default () => (
);
```
## 如何使用 {#how-to-use}
### 基础用法 {#basic-usage}
App 组件通过 `Context` 提供上下文方法调用,因而 useApp 需要作为子组件才能使用,我们推荐在应用中顶层包裹 App。
```tsx
import React from 'react';
import { App } from 'antd';
const MyPage: React.FC = () => {
const { message, notification, modal } = App.useApp();
message.success('Good!');
notification.info({ title: 'Good' });
modal.warning({ title: 'Good' });
// ....
// other message, notification, modal static function
return Hello world
;
};
const MyApp: React.FC = () => (
);
export default MyApp;
```
注意:App.useApp 必须在 App 之下方可使用。
### 与 ConfigProvider 先后顺序 {#sequence-with-configprovider}
App 组件只能在 `ConfigProvider` 之下才能使用 Design Token,如果需要使用其样式重置能力,则 ConfigProvider 与 App 组件必须成对出现。
```tsx
...
```
### 内嵌使用场景(如无必要,尽量不做嵌套) {#embedded-usage-scenarios}
```tsx
...
...
```
### 全局场景(redux 场景) {#global-scene-redux}
```tsx
// Entry component
import { App } from 'antd';
import type { MessageInstance } from 'antd/es/message/interface';
import type { ModalStaticFunctions } from 'antd/es/modal/confirm';
import type { NotificationInstance } from 'antd/es/notification/interface';
let message: MessageInstance;
let notification: NotificationInstance;
let modal: Omit;
export default () => {
const staticFunction = App.useApp();
message = staticFunction.message;
modal = staticFunction.modal;
notification = staticFunction.notification;
return null;
};
export { message, notification, modal };
```
```tsx
// sub page
import React from 'react';
import { Button, Space } from 'antd';
import { message } from './store';
export default () => {
const showMessage = () => {
message.success('Success!');
};
return (
Open message
);
};
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> 自 `antd@5.1.0` 版本开始提供该组件。
### App
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| component | 设置渲染元素,为 `false` 则不创建 DOM 节点 | ComponentType \| false | div | 5.11.0 | × |
| message | App 内 Message 的全局配置 | [MessageConfig](/components/message-cn/#messageconfig) | - | 5.3.0 | × |
| notification | App 内 Notification 的全局配置 | [NotificationConfig](/components/notification-cn/#notificationconfig) | - | 5.3.0 | × |
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
## FAQ
### CSS Var 在 `` 内不起作用 {#faq-css-var-component-false}
Ant Design v6 默认使用 CSS 变量。App 需要一个有效的 HTML 元素来承载 CSS 变量类名。将 `component` 设置为 `false` 时,App 仅提供上下文而不渲染根 DOM 节点,因此不会应用 App 根节点的类名和默认样式。在此模式下无法应用 `className`、`rootClassName` 和 `style` 属性,并会在开发环境下触发警告。如需消费这些样式,请保留默认的 `div` 或指定其他有效元素。
---
## auto-complete-cn
Source: https://ant.design/components/auto-complete-cn.md
---
category: Components
title: AutoComplete
subtitle: 自动完成
description: 输入框自动完成功能。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*g8THS4NpV6sAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*WERTQ6qvgEYAAAAAAAAAAAAADrJ8AQ/original
group:
title: 数据录入
order: 4
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 需要一个输入框而不是选择器。
- 需要输入建议/辅助提示。
和 Select 的区别是:
- AutoComplete 是一个带提示的文本输入框,用户可以自由输入,关键词是辅助**输入**。
- Select 是在限定的可选项中进行选择,关键词是**选择**。
## 代码演示 {#examples}
### 基本使用
基本使用,通过 `options` 设置自动完成的数据源。
```tsx
import React, { useState } from 'react';
import { AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [value, setValue] = useState('');
const [options, setOptions] = useState([]);
const [anotherOptions, setAnotherOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
const onSelect = (data: string) => {
console.log('onSelect', data);
};
const onChange = (data: string) => {
setValue(data);
};
return (
<>
setOptions(getPanelValue(text)),
}}
placeholder="input here"
/>
setAnotherOptions(getPanelValue(text)) }}
options={anotherOptions}
style={{ width: 200 }}
onSelect={onSelect}
onChange={onChange}
placeholder="control mode"
/>
>
);
};
export default App;
```
### 自定义选项
可以返回自定义的 `Option` label
```tsx
import React from 'react';
import { AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
const App: React.FC = () => {
const [options, setOptions] = React.useState([]);
const handleSearch = (value: string) => {
setOptions(() => {
if (!value || value.includes('@')) {
return [];
}
return ['gmail.com', '163.com', 'qq.com'].map((domain) => ({
label: `${value}@${domain}`,
value: `${value}@${domain}`,
}));
});
};
return (
);
};
export default App;
```
### 自定义输入组件
自定义输入组件。
```tsx
import React, { useState } from 'react';
import { AutoComplete, Input } from 'antd';
import type { AutoCompleteProps } from 'antd';
const { TextArea } = Input;
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const handleSearch = (value: string) => {
setOptions(
!value ? [] : [{ value }, { value: value + value }, { value: value + value + value }],
);
};
const handleKeyPress = (ev: React.KeyboardEvent) => {
console.log('handleKeyPress', ev);
};
const onSelect = (value: string) => {
console.log('onSelect', value);
};
return (
);
};
export default App;
```
### 不区分大小写
不区分大小写的 AutoComplete
```tsx
import React from 'react';
import { AutoComplete } from 'antd';
const options = [
{ value: 'Burns Bay Road' },
{ value: 'Downing Street' },
{ value: 'Wall Street' },
];
const App: React.FC = () => (
option!.value.toUpperCase().includes(inputValue.toUpperCase()),
}}
/>
);
export default App;
```
### 查询模式 - 确定类目
[查询模式: 确定类目](https://ant.design/docs/spec/reaction#lookup-patterns) 示例。
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { AutoComplete, Flex, Input } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css, prefixCls, cssVar } = props;
return {
categorySearch: css`
.${prefixCls}-select-dropdown-menu-item-group-title {
color: #666;
font-weight: ${cssVar.fontWeightStrong};
}
.${prefixCls}-select-dropdown-menu-item-group {
border-bottom: ${cssVar.lineWidth} ${cssVar.lineType} #f6f6f6;
}
.${prefixCls}-select-dropdown-menu-item {
padding-inline-start: ${cssVar.padding};
}
.${prefixCls}-select-dropdown-menu-item.show-all {
text-align: center;
cursor: default;
}
.${prefixCls}-select-dropdown-menu {
max-height: 300px;
}
`,
};
});
const Title: React.FC> = (props) => (
{props.title}
more
);
const renderItem = (title: string, count: number) => ({
value: title,
label: (
{title}
{count}
),
});
const options = [
{
label: ,
options: [renderItem('AntDesign', 10000), renderItem('AntDesign UI', 10600)],
},
{
label: ,
options: [renderItem('AntDesign UI FAQ', 60100), renderItem('AntDesign FAQ', 30010)],
},
{
label: ,
options: [renderItem('AntDesign design language', 100000)],
},
];
const App: React.FC = () => {
const { styles } = useStyles();
return (
);
};
export default App;
```
### 查询模式 - 不确定类目
[查询模式: 不确定类目](https://ant.design/docs/spec/reaction#lookup-patterns) 示例。
```tsx
import React, { useState } from 'react';
import { AutoComplete, Input } from 'antd';
import type { AutoCompleteProps } from 'antd';
const getRandomInt = (max: number, min = 0) => Math.floor(Math.random() * (max - min + 1)) + min;
const searchResult = (query: string) =>
Array.from({ length: getRandomInt(5) })
.join('.')
.split('.')
.map((_, idx) => {
const category = `${query}${idx}`;
return {
value: category,
label: (
Found {query} on{' '}
{category}
{getRandomInt(200, 100)} results
),
};
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const handleSearch = (value: string) => {
setOptions(value ? searchResult(value) : []);
};
const onSelect = (value: string) => {
console.log('onSelect', value);
};
return (
);
};
export default App;
```
### 自定义状态
使用 `status` 为 AutoComplete 添加状态,可选 `error` 或者 `warning`。
```tsx
import React, { useState } from 'react';
import { AutoComplete, Space } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const [anotherOptions, setAnotherOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
return (
setOptions(getPanelValue(text)),
}}
status="error"
style={{ width: 200 }}
/>
setAnotherOptions(getPanelValue(text)),
}}
status="warning"
style={{ width: 200 }}
/>
);
};
export default App;
```
### 多种形态
可选 `outlined` `filled` `borderless` `underlined` 四种形态。
```tsx
import React, { useState } from 'react';
import { AutoComplete, Flex } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
return (
setOptions(getPanelValue(text)) }}
onSelect={globalThis.console.log}
/>
setOptions(getPanelValue(text)) }}
onSelect={globalThis.console.log}
variant="filled"
/>
setOptions(getPanelValue(text)) }}
onSelect={globalThis.console.log}
variant="borderless"
/>
setOptions(getPanelValue(text))}
onSelect={globalThis.console.log}
variant="underlined"
/>
);
};
export default App;
```
### 自定义清除按钮
自定义清除按钮
```tsx
import React, { useState } from 'react';
import { CloseSquareFilled } from '@ant-design/icons';
import { AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
const mockVal = (str: string, repeat = 1) => ({
value: str.repeat(repeat),
});
const App: React.FC = () => {
const [options, setOptions] = useState([]);
const getPanelValue = (searchText: string) =>
!searchText ? [] : [mockVal(searchText), mockVal(searchText, 2), mockVal(searchText, 3)];
return (
<>
setOptions(getPanelValue(text)) }}
placeholder="UnClearable"
allowClear={false}
/>
setOptions(getPanelValue(text)) }}
placeholder="Customized clear icon"
allowClear={{ clearIcon: }}
/>
>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 AutoComplete 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { AutoComplete, Flex } from 'antd';
import type { AutoCompleteProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border-radius: 4px;
`,
}));
const stylesObject: AutoCompleteProps['styles'] = {
popup: {
root: { borderWidth: 1, borderColor: '#1890ff' },
list: { backgroundColor: 'rgba(240,240,240, 0.85)' },
listItem: { color: '#272727' },
},
};
const stylesFn: AutoCompleteProps['styles'] = ({
props,
}): GetProp => {
if (props.variant === 'filled') {
return {
popup: {
root: { borderWidth: 1, borderColor: '#ccc' },
list: { backgroundColor: 'rgba(240,240,240, 0.85)' },
listItem: { color: '#272727' },
},
};
}
return {};
};
const options: AutoCompleteProps['options'] = [
{ value: 'Burnaby' },
{ value: 'Seattle' },
{ value: 'Los Angeles' },
{ value: 'San Francisco' },
{ value: 'Meet student' },
];
const App: React.FC = () => {
const sharedProps: AutoCompleteProps = {
options,
classNames: {
root: classNames.root,
},
style: { width: 200 },
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| allowClear | 支持清除 | boolean \| { clearIcon?: ReactNode } | false | 5.8.0: 支持对象形式 |
| backfill | 使用键盘选择选项的时候把选中项回填到输入框中 | boolean | false | |
| children | 自定义输入框 | HTMLInputElement \| HTMLTextAreaElement \| React.ReactElement<InputProps> | <Input /> | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| ~~dataSource~~ | 自动完成的数据源,请使用 `options` 替代 | DataSourceItemType[] | - | - |
| defaultActiveFirstOption | 是否默认高亮第一个选项 | boolean | true | |
| defaultOpen | 是否默认展开下拉菜单 | boolean | - | |
| defaultValue | 指定默认选中的条目 | string | - | |
| disabled | 是否禁用 | boolean | false | |
| ~~dropdownClassName~~ | 下拉菜单的 className 属性,请使用 `classNames.popup.root` 替代 | string | - | - |
| ~~dropdownMatchSelectWidth~~ | 下拉菜单和输入框是否同宽,请使用 `popupMatchSelectWidth` 替代 | boolean \| number | true | - |
| ~~dropdownRender~~ | 自定义下拉框内容,使用 `popupRender` 替换 | (originNode: ReactNode) => ReactNode | - | 4.24.0 |
| popupRender | 自定义下拉框内容 | (originNode: ReactNode) => ReactNode | - | |
| ~~popupClassName~~ | 下拉菜单的 className 属性,使用 `classNames.popup.root` 替换 | string | - | 4.23.0 |
| ~~dropdownStyle~~ | 下拉菜单的 style 属性,使用 `styles.popup.root` 替换 | CSSProperties | - | |
| popupMatchSelectWidth | 下拉菜单和选择器同宽。默认将设置 `min-width`,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动 | boolean \| number | true | |
| ~~filterOption~~ | 是否根据输入项进行筛选。当其为一个函数时,会接收 `inputValue` `option` 两个参数,当 `option` 符合筛选条件时,应返回 true,反之则返回 false | boolean \| function(inputValue, option) | true | |
| getPopupContainer | 菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。[示例](https://codesandbox.io/s/4j168r7jw0) | function(triggerNode) | () => document.body | |
| notFoundContent | 当下拉列表为空时显示的内容 | ReactNode | - | |
| open | 是否展开下拉菜单 | boolean | - | |
| options | 数据化配置选项内容,相比 jsx 定义会获得更好的渲染性能 | { label, value }\[] | - | |
| placeholder | 输入框提示 | string | - | |
| showSearch | 搜索配置 | true \| [Object](#showsearch) | true | |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 |
| size | 控件大小 | `large` \| `medium` \| `small` | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| value | 指定当前选中的条目 | string | - | |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 |
| virtual | 设置 false 时关闭虚拟滚动 | boolean | true | 4.1.0 |
| onBlur | 失去焦点时的回调 | function() | - | |
| onChange | 选中 option,或 input 的 value 变化时,调用此函数 | function(value) | - | |
| ~~onDropdownVisibleChange~~ | 展开下拉菜单的回调,使用 `onOpenChange` 替换 | (open: boolean) => void | - | |
| onOpenChange | 展开下拉菜单的回调 | (open: boolean) => void | - | |
| onFocus | 获得焦点时的回调 | function() | - | |
| ~~onSearch~~ | 搜索补全项的时候调用 | function(value) | - | |
| onSelect | 被选中时调用,参数为选中项的 value 值 | function(value, option) | - | |
| onClear | 清除内容时的回调 | function | - | 4.6.0 |
| onInputKeyDown | 按键按下时回调 | (event: KeyboardEvent) => void | - | |
| onPopupScroll | 下拉列表滚动时的回调 | (event: UIEvent) => void | - | |
### showSearch
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| filterOption | 是否根据输入项进行筛选。当其为一个函数时,会接收 `inputValue` `option` 两个参数,当 `option` 符合筛选条件时,应返回 true,反之则返回 false | boolean \| function(inputValue, option) | true | |
| onSearch | 搜索补全项的时候调用 | function(value) | - | |
## 方法 {#methods}
| 名称 | 描述 | 版本 |
| ------- | -------- | ---- |
| blur() | 移除焦点 | |
| focus() | 获取焦点 | |
## Semantic DOM
https://ant.design/components/auto-complete-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Select)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| activeBorderColor | 激活态边框色 | string | #1677ff |
| activeOutlineColor | 激活态 outline 颜色 | string | rgba(5,145,255,0.1) |
| clearBg | 清空按钮背景色 | string | #ffffff |
| hoverBorderColor | 悬浮态边框色 | string | #4096ff |
| multipleItemBg | 多选标签背景色 | string | rgba(0,0,0,0.06) |
| multipleItemBorderColor | 多选标签边框色 | string | transparent |
| multipleItemBorderColorDisabled | 多选标签禁用边框色 | string | transparent |
| multipleItemColorDisabled | 多选标签禁用文本颜色 | string | rgba(0,0,0,0.25) |
| multipleItemHeight | 多选标签高度 | number | 24 |
| multipleItemHeightLG | 大号多选标签高度 | number | 32 |
| multipleItemHeightSM | 小号多选标签高度 | number | 16 |
| multipleSelectorBgDisabled | 多选框禁用背景 | string | rgba(0,0,0,0.04) |
| optionActiveBg | 选项激活态时背景色 | string | rgba(0,0,0,0.04) |
| optionFontSize | 选项字体大小 | number | 14 |
| optionHeight | 选项高度 | number | 32 |
| optionLineHeight | 选项行高 | LineHeight \| undefined | 1.5714285714285714 |
| optionPadding | 选项内间距 | Padding \| undefined | 5px 12px |
| optionSelectedBg | 选项选中时背景色 | string | #e6f4ff |
| optionSelectedColor | 选项选中时文本颜色 | string | rgba(0,0,0,0.88) |
| optionSelectedFontWeight | 选项选中时文本字重 | FontWeight \| undefined | 600 |
| selectorBg | 选框背景色 | string | #ffffff |
| showArrowPaddingInlineEnd | 箭头的行末内边距 | number | 18 |
| singleItemHeightLG | 单选大号回填项高度 | number | 40 |
| zIndexPopup | 下拉菜单 z-index | number | 1050 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| boxShadowSecondary | 控制元素二级阴影样式。 | string | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorBorderDisabled | 控制元素在禁用状态下的边框颜色。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorAffix | 控制表单控件前后缀在错误状态下的颜色。 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBgHover | 错误色的浅色背景色悬浮态 | string | |
| colorErrorBorderHover | 错误色的描边色悬浮态 | string | |
| colorErrorOutline | 控制输入组件错误状态下的外轮廓线颜色。 | string | |
| colorErrorText | 错误色的文本默认态 | string | |
| colorFillQuaternary | 最弱一级的填充色,适用于不易引起注意的色块,例如斑马纹、区分边界的色块等。 | string | |
| colorFillSecondary | 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 | string | |
| colorFillTertiary | 三级填充色用于勾勒出元素形体的场景,如 Slider、Segmented 等。如无强调需求的情况下,建议使用三级填色作为默认填色。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextPlaceholder | 控制占位文本的颜色。 | string | |
| colorTextQuaternary | 第四级文本色是最浅的文本色,例如表单的输入提示文本、禁用色文本等。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| colorWarningAffix | 控制表单控件前后缀在警告状态下的颜色。 | string | |
| colorWarningBg | 警戒色的浅色背景颜色 | string | |
| colorWarningBgHover | 警戒色的浅色背景色悬浮态 | string | |
| colorWarningHover | 警戒色的深色悬浮态 | string | |
| colorWarningOutline | 控制输入组件警告状态下的外轮廓线颜色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| controlItemBgActiveHover | 控制组件项在鼠标悬浮且激活状态下的背景颜色。 | string | |
| controlOutlineWidth | 控制输入组件的外轮廓线宽度。 | number | |
| controlPaddingHorizontal | 控制元素水平内间距。 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| motionEaseInQuint | 预设动效曲率 | string | |
| motionEaseOutCirc | 预设动效曲率 | string | |
| motionEaseOutQuint | 预设动效曲率 | string | |
| paddingSM | 控制元素的小内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
## FAQ
### 为何受控状态下使用 onSearch 无法输入中文? {#faq-controlled-onsearch-composition}
请使用 `onChange` 进行受控管理。`onSearch` 触发于搜索输入,与 `onChange` 时机不同。此外,点击选项时也不会触发 `onSearch` 事件。
相关 issue:[#18230](https://github.com/ant-design/ant-design/issues/18230) [#17916](https://github.com/ant-design/ant-design/issues/17916)
### 为何 options 为空时,受控 open 展开不会显示下拉菜单? {#faq-empty-options-controlled-open}
AutoComplete 组件本质上是 Input 输入框的一种扩展,当 `options` 为空时,显示空文本会让用户误以为该组件不可操作,实际上它仍然可以进行文本输入操作。因此,为了避免给用户带来困惑,当 `options` 为空时,`open` 属性为 `true` 也不会展示下拉菜单,需要与 `options` 属性配合使用。
---
## avatar-cn
Source: https://ant.design/components/avatar-cn.md
---
category: Components
title: Avatar
subtitle: 头像
description: 用来代表用户或事物,支持图片、图标或字符展示。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*JJBSS5lBG4IAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YbgyQaRGz-UAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 数据展示
order: 5
---
## 设计师专属 {#designers-exclusive}
安装 [Kitchen Sketch 插件 💎](https://kitchen.alipay.com),一键填充高逼格头像和文本。
## 代码演示 {#examples}
### 基本
头像有三种尺寸,两种形状可选。
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Space } from 'antd';
const App: React.FC = () => (
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
);
export default App;
```
### 类型
支持三种类型:图片、Icon 以及字符,其中 Icon 和字符型可以自定义图标颜色及背景色。
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Space } from 'antd';
const url = 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg';
const App: React.FC = () => (
} />
U
USER
} />
U
} />
);
export default App;
```
### 自动调整字符大小
对于字符型的头像,当字符串较长时,字体大小可以根据头像宽度自动调整。也可使用 `gap` 来设置字符距离左右两侧边界单位像素。
```tsx
import React, { useState } from 'react';
import { Avatar, Button } from 'antd';
const UserList = ['U', 'Lucy', 'Tom', 'Edward'];
const ColorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae'];
const GapList = [4, 3, 2, 1];
const App: React.FC = () => {
const [user, setUser] = useState(UserList[0]);
const [color, setColor] = useState(ColorList[0]);
const [gap, setGap] = useState(GapList[0]);
const changeUser = () => {
const index = UserList.indexOf(user);
setUser(index < UserList.length - 1 ? UserList[index + 1] : UserList[0]);
setColor(index < ColorList.length - 1 ? ColorList[index + 1] : ColorList[0]);
};
const changeGap = () => {
const index = GapList.indexOf(gap);
setGap(index < GapList.length - 1 ? GapList[index + 1] : GapList[0]);
};
return (
<>
{user}
ChangeUser
changeGap
>
);
};
export default App;
```
### 带徽标的头像
通常用于消息提示。
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
} />
} />
);
export default App;
```
### Avatar.Group
头像组合展现。
```tsx
import React from 'react';
import { AntDesignOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Divider, Tooltip } from 'antd';
const App: React.FC = () => (
<>
K
} />
} />
K
} />
} />
K
} />
} />
K
} />
} />
A
K
} />
} />
>
);
export default App;
```
### maxCount 包含溢出元素
使用 HOC 封装 `Avatar.Group`,添加 `overflowInFinal` 属性。开启后 `max.count` 表示总共显示的元素数量,会预留 1 个位置给溢出指示器。
```tsx
import React, { useState } from 'react';
import { toArray } from '@rc-component/util';
import { Avatar, Flex, InputNumber, Switch } from 'antd';
import type { AvatarGroupProps } from '../AvatarGroup';
const AvatarGroupOverflow: React.FC = (props) => {
const { overflowInFinal, ...restProps } = props;
const mergedMaxCount = props.max?.count ?? 3;
const childrenCount = toArray(props.children).length;
if (!overflowInFinal || mergedMaxCount >= childrenCount) {
return ;
}
return (
);
};
const App: React.FC = () => {
const [avatarCount, setAvatarCount] = useState(4);
const [overflowInFinal, setOverflowInFinal] = useState(true);
return (
Avatar count:
setAvatarCount(value!)}
aria-label="Avatar count"
mode="spinner"
/>
overflowInFinal:
{Array.from({ length: avatarCount }, (_, i) => (
{String.fromCharCode(65 + i)}
))}
);
};
export default App;
```
### 响应式尺寸
头像大小可以根据屏幕大小自动调整。
```tsx
import React from 'react';
import { AntDesignOutlined } from '@ant-design/icons';
import { Avatar } from 'antd';
const App: React.FC = () => (
}
/>
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Avatar
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| alt | 图像无法显示时的替代文本 | string | - | | × |
| gap | 字符类型距离左右两侧边界单位像素 | number | 4 | 4.3.0 | × |
| icon | 设置头像的自定义图标 | ReactNode | - | | × |
| shape | 指定头像的形状 | `circle` \| `square` | `circle` | | × |
| size | 设置头像的大小 | number \| `large` \| `medium` \| `small` \| { xs: number, sm: number, ...} | `medium` | 4.7.0 | × |
| src | 图片类头像的资源地址或者图片元素 | string \| ReactNode | - | ReactNode: 4.8.0 | × |
| srcSet | 设置图片类头像响应式资源地址 | string | - | | × |
| draggable | 图片是否允许拖动 | boolean \| `'true'` \| `'false'` | true | | × |
| crossOrigin | CORS 属性设置 | `'anonymous'` \| `'use-credentials'` \| `''` | - | 4.17.0 | × |
| onError | 图片加载失败的事件,返回 false 会关闭组件默认的 fallback 行为 | () => boolean | - | | × |
> Tip:你可以设置 `icon` 或 `children` 作为图片加载失败的默认 fallback 行为,优先级为 `icon` > `children`
### Avatar.Group 4.5.0+
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| max | 设置最多显示相关配置 | `{ count?: number; style?: CSSProperties; popover?: PopoverProps }` | - | 5.18.0 |
| ~~maxCount~~ | 已废弃,请使用 `max={{ count: number }}` | number | - | |
| ~~maxPopoverPlacement~~ | 已废弃,请使用 `max={{ popover: PopoverProps }}` | `top` \| `bottom` | `top` | |
| ~~maxPopoverTrigger~~ | 已废弃,请使用 `max={{ popover: PopoverProps }}` | `hover` \| `focus` \| `click` | `hover` | |
| ~~maxStyle~~ | 已废弃,请使用 `max={{ style: CSSProperties }}` | CSSProperties | - | |
| size | 设置头像的大小 | number \| `large` \| `medium` \| `small` \| { xs: number, sm: number, ...} | `medium` | 4.8.0 |
| shape | 设置头像的形状 | `circle` \| `square` | `circle` | 5.8.0 |
## 主题变量(Design Token){#design-token}
## 组件 Token (Avatar)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| containerSize | 头像尺寸 | number | 32 |
| containerSizeLG | 大号头像尺寸 | number | 40 |
| containerSizeSM | 小号头像尺寸 | number | 24 |
| groupBorderColor | 头像组边框颜色 | string | #ffffff |
| groupOverlapping | 头像组重叠宽度 | number | -8 |
| groupSpace | 头像组间距 | number | 4 |
| iconFontSize | 头像图标大小 | number | 18 |
| iconFontSizeLG | 大号头像图标大小 | string \| number | 24 |
| iconFontSizeSM | 小号头像图标大小 | number | 14 |
| textFontSize | 头像文字大小 | number | 14 |
| textFontSizeLG | 大号头像文字大小 | number | 14 |
| textFontSizeSM | 小号头像文字大小 | number | 14 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextPlaceholder | 控制占位文本的颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
---
## badge-cn
Source: https://ant.design/components/badge-cn.md
---
category: Components
title: Badge
subtitle: 徽标数
description: 图标右上角的圆形徽标数字。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*e0qITYqF394AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*v8EQT7KoGbcAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group: 数据展示
---
## 何时使用 {#when-to-use}
一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。
## 代码演示 {#examples}
### 基本
简单的徽章展示,当 `count` 为 `0` 时,默认不显示,但是可以使用 `showZero` 修改为显示。
```tsx
import React from 'react';
import { ClockCircleOutlined } from '@ant-design/icons';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
}>
);
export default App;
```
### 独立使用
不包裹任何元素即是独立使用,可自定样式展现。
> 在右上角的 badge 则限定为红色。
```tsx
import React, { useState } from 'react';
import { ClockCircleOutlined } from '@ant-design/icons';
import { Badge, Space, Switch } from 'antd';
const App: React.FC = () => {
const [show, setShow] = useState(true);
return (
setShow(!show)} />
: 0} />
);
};
export default App;
```
### 封顶数字
超过 `overflowCount` 的会显示为 `${overflowCount}+`,默认的 `overflowCount` 为 `99`。
```tsx
import React from 'react';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 讨嫌的小红点
没有具体的数字。
```tsx
import React from 'react';
import { NotificationOutlined } from '@ant-design/icons';
import { Badge, Space } from 'antd';
const App: React.FC = () => (
Link something
);
export default App;
```
### 动态
展示动态变化的效果。
```tsx
import React, { useState } from 'react';
import { MinusOutlined, PlusOutlined, QuestionOutlined } from '@ant-design/icons';
import { Avatar, Badge, Button, Space, Switch } from 'antd';
const App: React.FC = () => {
const [count, setCount] = useState(5);
const [show, setShow] = useState(true);
const increase = () => {
setCount(count + 1);
};
const decline = () => {
let newCount = count - 1;
if (newCount < 0) {
newCount = 0;
}
setCount(newCount);
};
const random = () => {
const newCount = Math.floor(Math.random() * 100);
setCount(newCount);
};
const onChange = (checked: boolean) => {
setShow(checked);
};
return (
} />
} />
} />
);
};
export default App;
```
### 可点击
用 a 标签进行包裹即可。
```tsx
import React from 'react';
import { Avatar, Badge } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义位置偏移
设置状态点的位置偏移,格式为 `[left, top]`,表示状态点距默认位置左侧、上方的偏移量。
```tsx
import React from 'react';
import { Avatar, Badge } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 大小
可以设置有数字徽标的大小。
```tsx
import React from 'react';
import { Avatar, Badge, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 状态点
用于表示状态的小圆点。
```tsx
import React from 'react';
import { Badge, Space } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 多彩徽标
我们添加了多种预设色彩的徽标样式,用作不同场景使用。如果预设值不能满足你的需求,可以设置为具体的色值。
```tsx
import React from 'react';
import { Badge, Divider, Space } from 'antd';
const colors = [
'pink',
'red',
'yellow',
'orange',
'cyan',
'green',
'blue',
'purple',
'geekblue',
'magenta',
'volcano',
'gold',
'lime',
];
const App: React.FC = () => (
<>
Presets
{colors.map((color) => (
))}
Custom
>
);
export default App;
```
### 缎带
使用缎带型的徽标。
```tsx
import React from 'react';
import { Badge, Card, Space } from 'antd';
const App: React.FC = () => (
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
and raises the spyglass.
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Badge 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Avatar, Badge, Card, Flex, Space } from 'antd';
import type { BadgeProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
import type { RibbonProps } from 'antd/es/badge/Ribbon';
const badgeClassNames = createStaticStyles(({ css }) => ({
indicator: css`
font-size: 10px;
`,
}));
const ribbonClassNames = createStaticStyles(({ css }) => ({
root: css`
width: 400px;
border: 1px solid #d9d9d9;
border-radius: 10px;
`,
}));
const badgeStyles: BadgeProps['styles'] = {
root: {
borderRadius: 8,
},
};
const ribbonStyles: RibbonProps['styles'] = {
indicator: {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
};
const badgeStylesFn: BadgeProps['styles'] = (info): GetProp => {
if (info.props.size === 'medium') {
return {
indicator: {
fontSize: 14,
backgroundColor: '#696FC7',
},
};
}
return {};
};
const ribbonStylesFn: RibbonProps['styles'] = (info): GetProp => {
if (info.props.color === '#696FC7') {
return {
content: {
fontWeight: 'bold',
},
indicator: {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
};
}
return {};
};
const App: React.FC = () => {
return (
This card has a customized ribbon with semantic classNames and styles.
This card has a customized ribbon with semantic classNames and styles.
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Badge
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| color | 自定义小圆点的颜色 | string | - | | × |
| count | 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏 | ReactNode | - | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.7.0 |
| dot | 不展示数字,只有一个小红点 | boolean | false | | × |
| offset | 设置状态点的位置偏移 | \[number, number] | - | | × |
| overflowCount | 展示封顶的数字值 | number | 99 | | × |
| showZero | 当数值为 0 时,是否展示 Badge | boolean | false | | × |
| size | 在设置了 `count` 的前提下有效,设置小圆点的大小 | `medium` \| `small` | - | - | × |
| status | 设置 Badge 为状态点 | `success` \| `processing` \| `default` \| `error` \| `warning` | - | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.7.0 |
| text | 在设置了 `status` 的前提下有效,设置状态点的文本 | ReactNode | - | | × |
| title | 设置鼠标放在状态点上时显示的文字。设置为 `null` 或 `false` 时移除原生 tooltip | string \| null \| false | - | 6.5.0 | × |
### Badge.Ribbon
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| color | 自定义缎带的颜色 | string | - | | × |
| placement | 缎带的位置,`start` 和 `end` 随文字方向(RTL 或 LTR)变动 | `start` \| `end` | `end` | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| text | 缎带中填入的内容 | ReactNode | - | | × |
## Semantic DOM
### Badge
https://ant.design/components/badge-cn/semantic.md
### Badge.Ribbon
https://ant.design/components/badge-cn/semantic_ribbon.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Badge)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| dotSize | 点状徽标尺寸 | number | 6 |
| indicatorHeight | 徽标高度 | string \| number | 20 |
| indicatorHeightSM | 小号徽标高度 | string \| number | 14 |
| indicatorZIndex | 徽标 z-index | string \| number | auto |
| paddingInline | 多字符徽标水平内边距 | string \| number | 8 |
| statusSize | 状态徽标尺寸 | number | 6 |
| textFontSize | 徽标文本尺寸 | number | 12 |
| textFontSizeSM | 小号徽标文本尺寸 | number | 12 |
| textFontWeight | 徽标文本粗细 | string \| number | normal |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorBorderBg | 控制元素背景边框的颜色。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorHover | 错误色的深色悬浮态 | string | |
| colorInfo | 用于表示操作信息的 Token 序列,如 Alert 、Tag、 Progress 等组件都有用到该组梯度变量。 | string | |
| colorInfoTextHover | 信息色的文本悬浮态。 | string | |
| colorSuccess | 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextPlaceholder | 控制占位文本的颜色。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseOutBack | 预设动效曲率 | string | |
---
## border-beam-cn
Source: https://ant.design/components/border-beam-cn.md
---
category: Components
group: 其他
title: BorderBeam
subtitle: 边框流光
description: 为容器边框提供持续流动的装饰性高亮效果。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*uae3QbkNCm8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*VcjGQLSrYdcAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
tag: 6.4.0
---
## 何时使用 {#when-to-use}
- 需要强化某个容器的视觉关注度,但又不希望引入业务状态语义时。
- 适合登录面板、推荐卡片、AI 模块、重点 CTA 区域等场景。
- 它是装饰性效果,不应替代焦点态、校验态或业务状态边框。
## 代码演示 {#examples}
### 基础用法
基础用法。使用 `BorderBeam` 修饰任意容器即可为边框添加持续流动的装饰性高亮效果。
```tsx
import React from 'react';
import { BorderBeam, Card } from 'antd';
const App: React.FC = () => (
Review task status, deployment health, and recent automation activity in one panel.
);
export default App;
```
### 鼠标悬浮时显示
默认隐藏边框流光,在鼠标 hover 到容器上时显示。
```tsx
import React from 'react';
import { BorderBeam, Card } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css, prefixCls, cssVar } = props;
return {
card: css`
width: 360px;
.${prefixCls}-border-beam {
opacity: 0;
transition: opacity ${cssVar.motionDurationMid};
&::before {
animation-play-state: paused;
}
}
&:hover {
.${prefixCls}-border-beam {
opacity: 1;
&::before {
animation-play-state: running;
}
}
}
`,
};
});
const Demo: React.FC = () => {
const { styles } = useStyles();
return (
The border beam appears when the pointer moves over this card.
);
};
export default Demo;
```
### 多条流光
通过 `count` 设置流光数量,多条流光会均匀分布在容器边框上,只接收正整数,默认值为 1。
```tsx
import React from 'react';
import { BorderBeam, Card, Flex } from 'antd';
const App: React.FC = () => (
Set count to distribute multiple beams evenly around the container border.
Set count to distribute multiple beams evenly around the container border.
);
export default App;
```
### 自定义容器
自定义容器也可以作为 `BorderBeam` 的宿主。由于流光层会被插入到子节点内部,并通过 `position: absolute` 贴合容器边缘,因此宿主元素需要提供定位上下文,通常设置 `position: relative` 即可。
```tsx
import React from 'react';
import { BorderBeam } from 'antd';
const panelStyle: React.CSSProperties = {
position: 'relative',
width: 420,
background: '#fff',
border: '1px solid #f0f0f0',
borderRadius: 8,
};
const contentStyle: React.CSSProperties = {
minHeight: 160,
padding: 24,
color: 'rgba(0, 0, 0, 0.88)',
lineHeight: 1.5715,
};
const App: React.FC = () => (
Review task status, deployment health, and recent automation activity in one custom
container.
);
export default App;
```
### 渐变色
展示 6 组渐变流光配色,可切换查看不同效果。
```tsx
import React from 'react';
import { BorderBeam, Card, Flex, Segmented, Tag, Typography } from 'antd';
import type { BorderBeamGradient } from 'antd';
const presets: Array<{
key: string;
name: string;
usage: string;
description: string;
color: BorderBeamGradient;
}> = [
{
key: 'ocean',
name: 'Ocean',
usage: 'Dashboard',
description: 'A calm blue-green accent that works well for data views and cloud tooling.',
color: [
{ color: '#1677ff', percent: 0 },
{ color: '#36cfc9', percent: 52 },
{ color: '#95de64', percent: 100 },
],
},
{
key: 'sunset',
name: 'Sunset',
usage: 'Upgrade',
description: 'A warm highlight for upgrade prompts, featured cards, and marketing blocks.',
color: [
{ color: '#ff7a45', percent: 0 },
{ color: '#ff4d4f', percent: 49 },
{ color: '#ff85c0', percent: 100 },
],
},
{
key: 'aurora',
name: 'Aurora',
usage: 'AI',
description:
'A vivid cool-toned beam suited for AI assistants, copilots, and automation panels.',
color: [
{ color: '#7c3aed', percent: 0 },
{ color: '#06b6d4', percent: 57 },
{ color: '#67e8f9', percent: 100 },
],
},
{
key: 'forest',
name: 'Forest',
usage: 'Recommendation',
description:
'A bright natural palette that feels good on recommendation and growth-oriented cards.',
color: [
{ color: '#22c55e', percent: 0 },
{ color: '#a3e635', percent: 54 },
{ color: '#facc15', percent: 100 },
],
},
{
key: 'ember',
name: 'Ember',
usage: 'Alert',
description: 'A high-energy warm gradient for important alerts, launch cards, and hot paths.',
color: [
{ color: '#fa541c', percent: 0 },
{ color: '#ff7875', percent: 46 },
{ color: '#ffd666', percent: 100 },
],
},
{
key: 'nebula',
name: 'Nebula',
usage: 'Labs',
description: 'A cool purple-pink mix that fits experimental modules and product lab surfaces.',
color: [
{ color: '#2f54eb', percent: 0 },
{ color: '#722ed1', percent: 44 },
{ color: '#ff85c0', percent: 100 },
],
},
];
const defaultPresetKey = presets[0].key;
const App: React.FC = () => {
const [currentPresetKey, setCurrentPresetKey] = React.useState(defaultPresetKey);
const currentPreset = presets.find((preset) => preset.key === currentPresetKey) ?? presets[0];
return (
({
label: preset.name,
value: preset.key,
}))}
value={currentPresetKey}
onChange={(value) => setCurrentPresetKey(value as string)}
/>
{currentPreset.usage}}
styles={{
body: {
display: 'flex',
flexDirection: 'column',
gap: 16,
},
}}
>
{currentPreset.description}
{currentPreset.color.map((item) => (
{item.color} · {item.percent}%
))}
Stop positions use the public 0-100 input range.
);
};
export default App;
```
### 动画时长
通过 `duration` 控制流光完成一圈所需时间,单位为秒,默认值为 6 秒。
```tsx
import React from 'react';
import { BorderBeam, Card, Flex, Tag, Typography } from 'antd';
const durations = [
{
name: 'Fast',
seconds: 3,
description: 'A quick loop for temporary highlights and active modules.',
},
{
name: 'Default',
seconds: 6,
description: 'The original pacing for most emphasized containers.',
},
{
name: 'Slow',
seconds: 12,
description: 'A calmer loop for persistent panels and ambient surfaces.',
},
];
const App: React.FC = () => (
{durations.map(({ name, seconds, description }) => (
{seconds}s}>
{description}
))}
);
export default App;
```
### 尺寸
通过 `size` 控制流光可见段的尺寸,默认值为 `100px`,数字类型按像素处理。
```tsx
import React from 'react';
import { BorderBeam, Card, Tag, Typography } from 'antd';
const sizes: Array<{
name: string;
size?: number | string;
bodyMinHeight: number;
description: string;
spanFull?: boolean;
}> = [
{
name: 'Default',
bodyMinHeight: 112,
description: 'Uses the default 100px visible beam segment.',
},
{
name: 'Compact',
size: 56,
bodyMinHeight: 112,
description: 'Keeps the highlight shorter for dense card groups.',
},
{
name: 'Extended',
size: 160,
bodyMinHeight: 192,
description: 'Creates a longer highlight for wider feature panels.',
spanFull: true,
},
];
const App: React.FC = () => (
{sizes.map(({ name, size, bodyMinHeight, description, spanFull }) => (
{size ?? 100}px}
styles={{ body: { minHeight: bodyMinHeight, display: 'flex', alignItems: 'center' } }}
>
{description}
))}
);
export default App;
```
### 线宽
通过 `lineWidth` 调整单个 BorderBeam 的流光线宽,默认值为 `1px`,数字类型按像素处理。
```tsx
import React from 'react';
import { BorderBeam, Card } from 'antd';
const App: React.FC = () => (
Set lineWidth to match the border width of this container.
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### BorderBeam
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| children | 装饰内容 | `ReactNode` | - | 6.4.0 | × |
| color | 流光颜色配置,支持单色字符串或渐变停靠点数组。`percent` 使用 `0 ~ 100` 的输入区间,组件会在内部为尾部透明过渡预留空间 | `string \| { color: string; percent: number }[]` | - | 6.4.0 | × |
| count | 流光数量 | number | 1 | 6.6.0 | × |
| duration | 流光完成一圈动画的时间,单位秒 | number | 6 | 6.5.0 | × |
| lineWidth | 流光线宽,数字类型按像素处理 | `number \| string` | `1px` | 6.5.0 | × |
| outset | 流光层相对容器边缘的外扩距离,遇到裁剪容器时可设为 `0` | `number \| string` | - | 6.4.0 | × |
| size | 流光可见段的尺寸,数字类型按像素处理 | `number \| string` | 100 | 6.5.0 | × |
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
## FAQ
### 开启减少动态效果后会怎样? {#faq-reduced-motion}
`BorderBeam` 会将流光视为装饰效果。当命中 `prefers-reduced-motion: reduce` 时,组件会隐藏 beam 效果。
### `color` 中的 `percent` 表示什么? {#faq-color-percent}
`percent` 表示渐变停靠点的输入位置,取值范围为 `0 ~ 100`。组件会将这些停靠点映射到可见 beam 段内,并为尾部透明过渡保留空间,以保持流光尾迹连续可见。
### 为什么 `BorderBeam` 没有效果? {#faq-not-working}
`BorderBeam` 需要通过 `children` 获取实际 DOM 节点,并将流光层插入到该节点中。请确保被包裹的内容是原生 DOM 元素,或是正确透传 `ref` 到 DOM 的 React 组件,否则组件无法定位真实容器,也就无法渲染流光效果。
流光层使用 `position: absolute` 定位,因此被索引到的 DOM 节点还需要提供定位上下文,通常可以为它设置 `position: relative`。`BorderBeam` 不会主动检测或修正子节点的定位样式。
为保证性能,`children` 是否可以插入以及其定位信息会在初始化时判断,后续不会持续监听子节点结构或定位样式变化。
### 如何让流光边框跟随容器圆角? {#faq-radius}
`BorderBeam` 会在初始化时读取实际容器的计算后 `border-radius`。这个能力更适合 `Card` 这类单容器子节点场景;若子节点结构较复杂,建议直接把圆角写在实际容器根节点上,以获得更稳定的结果。
为保证性能,圆角计算完成后不会持续重新测量。后续由尺寸、祖先样式或子节点内部状态引起的圆角变化,不保证自动重新同步。动画轨迹在运行时可能会做内部平滑处理。
例如:
```tsx
const radius = 24;
;
```
---
## breadcrumb-cn
Source: https://ant.design/components/breadcrumb-cn.md
---
category: Components
group: 导航
title: Breadcrumb
subtitle: 面包屑
description: 显示当前页面在系统层级结构中的位置,并能向上返回。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*I5a2Tpqs3y0AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Tr90QKrE_LcAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 当系统拥有超过两级以上的层级结构时;
- 当需要告知用户『你在哪里』时;
- 当需要向上导航的功能时。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => {
return (
Application Center,
},
{
title: Application List ,
},
{
title: 'An Application',
},
]}
/>
);
};
export default App;
```
### 带有图标的
图标放在文字前面。第三方图标库(如 lucide、react-icons)渲染出的裸 `` 也会与文字垂直居中并保持间距。
```tsx
import React from 'react';
import { HomeOutlined, UserOutlined } from '@ant-design/icons';
import { Breadcrumb } from 'antd';
// Icons from third-party libraries (e.g. lucide, react-icons) render as a bare ``
// rather than an `.anticon` wrapper. It stays centred with, and spaced from, the label.
const ChartIcon: React.FC = () => (
);
const App: React.FC = () => (
,
},
{
href: '',
title: (
<>
Application List
>
),
},
{
href: '',
title: (
<>
Dashboard
>
),
},
{
title: 'Application',
},
]}
/>
);
export default App;
```
### 带有参数的
带有路由参数的。
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 分隔符
使用 `separator=">"` 可以自定义分隔符。
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 带下拉菜单的面包屑
面包屑支持下拉菜单。
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const menuItems = [
{
key: '1',
label: (
General
),
},
{
key: '2',
label: (
Layout
),
},
{
key: '3',
label: (
Navigation
),
},
];
const App: React.FC = () => (
Component,
},
{
title: General ,
menu: { items: menuItems },
},
{
title: 'Button',
},
]}
/>
);
export default App;
```
### 独立的分隔符
自定义单独的分隔符。
```tsx
import React from 'react';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Breadcrumb 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Breadcrumb, Flex } from 'antd';
import type { BreadcrumbProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 8px;
border-radius: 4px;
`,
item: css`
color: #1890ff;
`,
separator: css`
color: rgba(0, 0, 0, 0.45);
`,
}));
const styles: BreadcrumbProps['styles'] = {
root: { border: '1px solid #f0f0f0', padding: 8, borderRadius: 4 },
item: { color: '#1890ff' },
separator: { color: 'rgba(0, 0, 0, 0.45)' },
};
const stylesFn: BreadcrumbProps['styles'] = (
info,
): GetProp => {
const items = info.props.items || [];
if (items.length > 2) {
return {
root: { border: '1px solid #F5EFFF', padding: 8, borderRadius: 4 },
item: { color: '#8F87F1' },
};
}
return {};
};
const items = [
{ title: 'Ant Design' },
{ title: Component },
{ title: 'Breadcrumb' },
];
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Breadcrumb
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| dropdownIcon | 自定义下拉图标 | ReactNode | ` ` | 6.2.0 | 6.2.0 |
| items | 路由栈信息(>=5.3.0 推荐使用,旧版请使用 `Breadcrumb.Item` 子组件方式) | [ItemType\[\]](#itemtype) | - | 5.3.0 | × |
| itemRender | 自定义链接函数,和 react-router 配合使用,详见[示例](#use-with-browserhistory) | (route, params, routes, paths) => ReactNode | - | | × |
| params | 路由的参数 | object | - | | × |
| separator | 分隔符自定义 | ReactNode | `/` | | 6.0.0 |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
### ItemType
> type ItemType = Omit<[RouteItemType](#routeitemtype), 'title' | 'path'> | [SeparatorType](#separatortype)
### RouteItemType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| className | 自定义类名 | string | - | |
| dropdownProps | 弹出下拉菜单的自定义配置 | [Dropdown](/components/dropdown-cn) | - | |
| href | 链接的目的地,不能和 `path` 共用 | string | - | |
| path | 拼接路径,每一层都会拼接前一个 `path` 信息。不能和 `href` 共用 | string | - | |
| menu | 菜单配置项 | [MenuProps](/components/menu-cn/#api) | - | 4.24.0 |
| onClick | 单击事件 | (e:MouseEvent) => void | - | |
| title | 名称 | ReactNode | - | 5.3.0 |
### SeparatorType
```ts
const item = {
type: 'separator', // Must have
separator: '/',
};
```
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------- | -------------- | ----------- | ------ | ----- |
| type | 标记为分隔符 | `separator` | | 5.3.0 |
| separator | 要显示的分隔符 | ReactNode | `/` | 5.3.0 |
### 和 browserHistory 配合 {#use-with-browserhistory}
和 react-router 一起使用时,默认生成的 url 路径是带有 `#` 的,如果和 browserHistory 一起使用的话,你可以使用 `itemRender` 属性定义面包屑链接。
```jsx
import { Link } from 'react-router';
const items = [
{
path: '/index',
title: 'home',
},
{
path: '/first',
title: 'first',
children: [
{
path: '/general',
title: 'General',
},
{
path: '/layout',
title: 'Layout',
},
{
path: '/navigation',
title: 'Navigation',
},
],
},
{
path: '/second',
title: 'second',
},
];
function itemRender(currentRoute, params, items, paths) {
const isLast = currentRoute?.path === items[items.length - 1]?.path;
return isLast ? (
{currentRoute.title}
) : (
{currentRoute.title}
);
}
return ;
```
## Semantic DOM
https://ant.design/components/breadcrumb-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Breadcrumb)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| iconFontSize | 图标大小 | number | 14 |
| itemColor | 面包屑项文字颜色 | string | rgba(0,0,0,0.45) |
| lastItemColor | 最后一项文字颜色 | string | rgba(0,0,0,0.88) |
| linkColor | 链接文字颜色 | string | rgba(0,0,0,0.45) |
| linkHoverColor | 链接文字悬浮颜色 | string | rgba(0,0,0,0.88) |
| separatorColor | 分隔符颜色 | string | rgba(0,0,0,0.45) |
| separatorMargin | 分隔符外间距 | number | 8 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgTextHover | 控制文本在悬停状态下的背景色。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| lineHeight | 文本行高 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| paddingXXS | 控制元素的极小内间距。 | number | |
---
## button-cn
Source: https://ant.design/components/button-cn.md
---
category: Components
title: Button
subtitle: 按钮
description: 按钮用于开始一个即时操作。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*7va7RKs3YzIAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*3T4cRqxH9-8AAAAAAAAAAAAADrJ8AQ/original
designUrl: /docs/spec/buttons-cn
demo:
cols: 2
group:
title: 通用
order: 1
---
## 何时使用 {#when-to-use}
标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。
在 Ant Design 中我们提供了五种按钮。
- 🔵 主按钮:用于主行动点,一个操作区域只能有一个主按钮。
- ⚪️ 默认按钮:用于没有主次之分的一组行动点。
- 😶 虚线按钮:常用于添加操作。
- 🔤 文本按钮:用于最次级的行动点。
- 🔗 链接按钮:一般用于链接,即导航至某位置。
以及四种状态属性与上面配合使用。
- ⚠️ 危险:删除/移动/修改权限等危险操作,一般需要二次确认。
- 👻 幽灵:用于背景色比较复杂的地方,常用在首页/产品页等展示场景。
- 🚫 禁用:行动点不可用的时候,一般需要文案解释。
- 🔃 加载中:用于异步操作等待反馈的时候,也可以避免多次提交。
## 代码演示 {#examples}
### 语法糖
通过 `type` 语法糖,使用预设的按钮样式:主按钮、次按钮、虚线按钮、文本按钮和链接按钮。推荐主按钮在同一个操作区域最多出现一次。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary Button
Default Button
Dashed Button
Text Button
Link Button
);
export default App;
```
### 颜色与变体
同时设置 `color` 和 `variant` 属性,可以衍生出更多的变体按钮。
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex } from 'antd';
import { useResponsive } from 'antd-style';
const App: React.FC = () => {
const { xxl } = useResponsive();
return (
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
Solid
Outlined
Dashed
Filled
Text
Link
);
};
export default App;
```
### 按钮图标
可以通过 `icon`属性添加图标。
```tsx
import React from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Flex, Tooltip } from 'antd';
const App: React.FC = () => (
} />
A
}>
Search
} />
}>Search
} />
}>Search
} />
}>
Search
} href="https://www.google.com" target="_blank" />
);
export default App;
```
### 按钮图标位置
通过设置 `iconPlacement` 为 `start` 或 `end` 分别设置按钮图标的位置。
```tsx
import React, { useState } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Divider, Flex, Radio, Space, Tooltip } from 'antd';
const App: React.FC = () => {
const [position, setPosition] = useState<'start' | 'end'>('end');
return (
<>
setPosition(e.target.value)}>
start
end
Preview
} />
A
} iconPlacement={position}>
Search
} />
} iconPlacement={position}>
Search
} />
} type="text" iconPlacement={position}>
Search
} />
} iconPlacement={position}>
Search
}
href="https://www.google.com"
target="_blank"
iconPlacement={position}
/>
Loading
>
);
};
export default App;
```
### 按钮尺寸
按钮有大、中、小三种尺寸。
通过设置 `size` 为 `large` `small` 分别把按钮设为大、小尺寸。若不设置 `size`,则尺寸默认为 `medium`。
```tsx
import React, { useState } from 'react';
import { DownloadOutlined } from '@ant-design/icons';
import { Button, Divider, Flex, Radio } from 'antd';
import type { ConfigProviderProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const App: React.FC = () => {
const [size, setSize] = useState('large'); // default is 'medium'
return (
<>
setSize(e.target.value)}>
Large
Medium
Small
Preview
Primary
Default
Dashed
Link
} size={size} />
} size={size} />
} size={size} />
} size={size}>
Download
} size={size}>
Download
>
);
};
export default App;
```
### 不可用状态
添加 `disabled` 属性即可让按钮处于不可用状态,同时按钮样式也会改变。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Primary(disabled)
Default
Default(disabled)
Dashed
Dashed(disabled)
Text
Text(disabled)
Link
Link(disabled)
Href Primary
Href Primary(disabled)
Danger Default
Danger Default(disabled)
Danger Text
Danger Text(disabled)
Danger Link
Danger Link(disabled)
Ghost
Ghost(disabled)
);
export default App;
```
### 加载中状态
添加 `loading` 属性即可让按钮处于加载状态,`loading.icon` 可以自定义加载图标,最后三个按钮演示点击后进入加载状态。
```tsx
import React, { useState } from 'react';
import { PoweroffOutlined, SyncOutlined } from '@ant-design/icons';
import { Button, Flex } from 'antd';
const App: React.FC = () => {
const [loadings, setLoadings] = useState([]);
const enterLoading = (index: number) => {
console.log('Start loading:', index);
setLoadings((prevLoadings) => {
const newLoadings = [...prevLoadings];
newLoadings[index] = true;
return newLoadings;
});
setTimeout(() => {
setLoadings((prevLoadings) => {
const newLoadings = [...prevLoadings];
newLoadings[index] = false;
return newLoadings;
});
}, 3000);
};
return (
Loading
Loading
} loading />
}}>
Loading Icon
enterLoading(0)}>
Icon Start
enterLoading(2)}
iconPlacement="end"
>
Icon End
}
loading={loadings[1]}
onClick={() => enterLoading(1)}
>
Icon Replace
}
loading={loadings[3]}
onClick={() => enterLoading(3)}
/>
}
loading={loadings[3] && { icon: }}
onClick={() => enterLoading(3)}
>
Loading Icon
);
};
export default App;
```
### 多个按钮组合
按钮组合使用时,推荐使用 1 个主操作 + n 个次操作,3 个以上操作时把更多操作放到 [Dropdown](/components/dropdown-cn/#dropdown-demo-dropdown-button) 中组合使用。
```tsx
import React from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Flex, Space } from 'antd';
const onMenuClick: MenuProps['onClick'] = (e) => {
console.log('click', e);
};
const items = [
{
key: '1',
label: '1st item',
},
{
key: '2',
label: '2nd item',
},
{
key: '3',
label: '3rd item',
},
];
const App: React.FC = () => (
primary
secondary
Actions
} />
);
export default App;
```
### 幽灵按钮
幽灵按钮将按钮的内容反色,背景变为透明,常用在有色背景上。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Default
Dashed
Danger
);
export default App;
```
### 危险按钮
在 4.0 之后,危险成为一种按钮属性而不是按钮类型。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Default
Dashed
Text
Link
);
export default App;
```
### Block 按钮
`block` 属性将使按钮适合其父宽度。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
Primary
Default
Dashed
disabled
text
Link
);
export default App;
```
### 渐变按钮
自定义为渐变背景按钮。
```tsx
import React from 'react';
import { AntDesignOutlined } from '@ant-design/icons';
import { Button, ConfigProvider, Space } from 'antd';
import { createStyles } from 'antd-style';
const useStyle = createStyles(({ cssVar, prefixCls, css }) => ({
linearGradientButton: css`
&.${prefixCls}-btn-primary:not([disabled]):not(.${prefixCls}-btn-dangerous) {
> span {
position: relative;
}
&::before {
content: '';
background: linear-gradient(135deg, #6253e1, #04befe);
position: absolute;
inset: -1px;
opacity: 1;
transition: all ${cssVar.motionDurationSlow};
border-radius: inherit;
}
&:hover::before {
opacity: 0;
}
}
`,
}));
const App: React.FC = () => {
const { styles } = useStyle();
return (
}>
Gradient Button
Button
);
};
export default App;
```
### 自定义按钮波纹
波纹效果带来了灵动性,你也可以使用 [`@ant-design/happy-work-theme`](https://github.com/ant-design/happy-work-theme) 提供的 HappyProvider 实现动态波纹效果。
```tsx
import React from 'react';
import { HappyProvider } from '@ant-design/happy-work-theme';
import { Button, ConfigProvider, Flex } from 'antd';
import type { ConfigProviderProps, GetProp } from 'antd';
type WaveConfig = GetProp;
// Prepare effect holder
const createHolder = (node: HTMLElement) => {
const { borderWidth } = getComputedStyle(node);
const borderWidthNum = Number.parseInt(borderWidth, 10);
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.inset = `-${borderWidthNum}px`;
div.style.borderRadius = 'inherit';
div.style.background = 'transparent';
div.style.zIndex = '999';
div.style.pointerEvents = 'none';
div.style.overflow = 'hidden';
node.appendChild(div);
return div;
};
const createDot = (holder: HTMLElement, color: string, left: number, top: number, size = 0) => {
const dot = document.createElement('div');
dot.style.position = 'absolute';
dot.style.insetInlineStart = `${left}px`;
dot.style.top = `${top}px`;
dot.style.width = `${size}px`;
dot.style.height = `${size}px`;
dot.style.borderRadius = '50%';
dot.style.background = color;
dot.style.transform = 'translate3d(-50%, -50%, 0)';
dot.style.transition = 'all 1s ease-out';
holder.appendChild(dot);
return dot;
};
// Inset Effect
const showInsetEffect: WaveConfig['showEffect'] = (node, { event, component }) => {
if (component !== 'Button') {
return;
}
const holder = createHolder(node);
const rect = holder.getBoundingClientRect();
const left = event.clientX - rect.left;
const top = event.clientY - rect.top;
const dot = createDot(holder, 'rgba(255, 255, 255, 0.65)', left, top);
// Motion
requestAnimationFrame(() => {
dot.ontransitionend = () => {
holder.remove();
};
dot.style.width = '200px';
dot.style.height = '200px';
dot.style.opacity = '0';
});
};
// Shake Effect
const showShakeEffect: WaveConfig['showEffect'] = (node, { component }) => {
if (component !== 'Button') {
return;
}
const seq = [0, -15, 15, -5, 5, 0];
const itv = 10;
let steps = 0;
const loop = () => {
cancelAnimationFrame((node as any).effectTimeout);
(node as any).effectTimeout = requestAnimationFrame(() => {
const currentStep = Math.floor(steps / itv);
const current = seq[currentStep];
const next = seq[currentStep + 1];
if (next === undefined || next === null) {
node.style.transform = '';
node.style.transition = '';
return;
}
// Trans from current to next by itv
const angle = current + ((next - current) / itv) * (steps % itv);
node.style.transform = `rotate(${angle}deg)`;
node.style.transition = 'none';
steps += 1;
loop();
});
};
loop();
};
// Component
const Wrapper: React.FC = ({ name, ...wave }) => (
{name}
);
const Demo: React.FC = () => (
Happy Work
);
export default Demo;
```
### 移除两个汉字之间的空格
我们默认在两个汉字之间添加空格,可以通过设置 `autoInsertSpace` 为 `false` 关闭。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const App: React.FC = () => (
确定
确定
);
export default App;
```
### 自定义禁用样式背景
自定义disable下的背景颜色(适用 `default` 和 `dashed` 类型)
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex } from 'antd';
const App: React.FC = () => (
Primary Button
Default Button
Dashed Button
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Button 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
import type { ButtonProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ cssVar }) => ({
root: {
border: `${cssVar.lineWidth} ${cssVar.lineType} ${cssVar.colorBorder}`,
borderRadius: cssVar.borderRadius,
padding: `${cssVar.paddingXS} ${cssVar.padding}`,
height: 'auto',
},
content: {
color: cssVar.colorText,
},
}));
const stylesObject: ButtonProps['styles'] = {
root: {
boxShadow: '0 1px 2px 0 rgba(0,0,0,0.05)',
},
};
const stylesFn: ButtonProps['styles'] = (info): GetProp => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
Object
Function
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
通过设置 Button 的属性来产生不同的按钮样式,推荐顺序为:`type` -> `shape` -> `size` -> `loading` -> `disabled`。
按钮的属性说明如下:
| 属性 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| autoInsertSpace | 我们默认提供两个汉字之间的空格,可以设置 `autoInsertSpace` 为 `false` 关闭 | boolean | `true` | 5.17.0 | 5.17.0 |
| block | 将按钮宽度调整为其父宽度的选项 | boolean | false | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 | 6.0.0 |
| color | 设置按钮的颜色 | `default` \| `primary` \| `danger` \| [PresetColors](#presetcolors) | `variant="solid"` 时为 `primary` | `default`、`primary` 和 `danger`: 5.21.0, `PresetColors`: 5.23.0, `solid` 默认颜色: 6.4.0 | 5.25.0 |
| danger | 语法糖,设置危险按钮。当设置 `color` 时会以后者为准 | boolean | false | | × |
| disabled | 设置按钮失效状态 | boolean | false | | × |
| ghost | 幽灵属性,使按钮背景透明 | boolean | false | | × |
| href | 点击跳转的地址,指定此属性 button 的行为和 a 链接一致 | string | - | | × |
| htmlType | 设置 `button` 原生的 `type` 值,可选值请参考 [HTML 标准](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/button#type) | `submit` \| `reset` \| `button` | `button` | | × |
| icon | 设置按钮的图标组件 | ReactNode | - | | × |
| iconPlacement | 设置按钮图标组件的位置 | `start` \| `end` | `start` | - | × |
| ~~iconPosition~~ | 设置按钮图标组件的位置,请使用 `iconPlacement` 替换 | `start` \| `end` | `start` | 5.17.0 | × |
| loading | 设置按钮载入状态 | boolean \| { delay: number, icon: ReactNode } | false | icon: 5.23.0 | × |
| loadingIcon | (仅支持全局配置)设置按钮的加载图标 | ReactNode | ` ` | | 6.3.0 |
| onClick | 点击按钮时的回调 | (event: React.MouseEvent) => void | - | | × |
| shape | 设置按钮形状 | `default` \| `circle` \| `round` | `default` | | 5.27.0 |
| size | 设置按钮大小 | `large` \| `medium` \| `small` | `medium` | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 | 6.0.0 |
| target | 相当于 a 链接的 target 属性,href 存在时生效 | string | - | | × |
| type | 语法糖,设置按钮类型。当设置 `variant` 与 `color` 时以后者为准 | `primary` \| `dashed` \| `link` \| `text` \| `default` | `default` | | × |
| variant | 设置按钮的变体 | `outlined` \| `dashed` \| `solid` \| `filled` \| `text` \| `link` | - | 5.21.0 | 5.25.0 |
支持原生 button 的其他所有属性。
### PresetColors
> type PresetColors = 'blue' | 'purple' | 'cyan' | 'green' | 'magenta' | 'pink' | 'red' | 'orange' | 'yellow' | 'volcano' | 'geekblue' | 'lime' | 'gold';
## Semantic DOM
https://ant.design/components/button-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Button)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| contentFontSize | 按钮内容字体大小 | number | 14 |
| contentFontSizeLG | 大号按钮内容字体大小 | number | 16 |
| contentFontSizeSM | 小号按钮内容字体大小 | number | 14 |
| dangerColor | 危险按钮文本颜色 | string | #fff |
| dangerShadow | 危险按钮阴影 | string | 0 2px 0 rgba(255,38,5,0.06) |
| dashedBgDisabled | type='dashed' 禁用状态下的背景颜色 | string | rgba(0,0,0,0.04) |
| defaultActiveBg | 默认按钮激活态背景色 | string | #ffffff |
| defaultActiveBorderColor | 默认按钮激活态边框颜色 | string | #0958d9 |
| defaultActiveColor | 默认按钮激活态文字颜色 | string | #0958d9 |
| defaultBg | 默认按钮背景色 | string | #ffffff |
| defaultBgDisabled | type='default' 禁用状态下的背景颜色 | string | rgba(0,0,0,0.04) |
| defaultBorderColor | 默认按钮边框颜色 | string | #d9d9d9 |
| defaultColor | 默认按钮文本颜色 | string | rgba(0,0,0,0.88) |
| defaultGhostBorderColor | 默认幽灵按钮边框颜色 | string | #ffffff |
| defaultGhostColor | 默认幽灵按钮文本颜色 | string | #ffffff |
| defaultHoverBg | 默认按钮悬浮态背景色 | string | #ffffff |
| defaultHoverBorderColor | 默认按钮悬浮态边框颜色 | string | #4096ff |
| defaultHoverColor | 默认按钮悬浮态文本颜色 | string | #4096ff |
| defaultShadow | 默认按钮阴影 | string | 0 2px 0 rgba(0,0,0,0.02) |
| fontWeight | 文字字重 | FontWeight \| undefined | 400 |
| ghostBg | 幽灵按钮背景色 | string | transparent |
| iconGap | 图标文字间距 | Gap \| undefined | 8 |
| linkHoverBg | 链接按钮悬浮态背景色 | string | transparent |
| onlyIconSize | 只有图标的按钮图标尺寸 | string \| number | inherit |
| onlyIconSizeLG | 大号只有图标的按钮图标尺寸 | string \| number | inherit |
| onlyIconSizeSM | 小号只有图标的按钮图标尺寸 | string \| number | inherit |
| paddingInline | 按钮横向内间距 | PaddingInline \| undefined | 15 |
| paddingInlineLG | 大号按钮横向内间距 | PaddingInline \| undefined | 15 |
| paddingInlineSM | 小号按钮横向内间距 | PaddingInline \| undefined | 7 |
| primaryColor | 主要按钮文本颜色 | string | #fff |
| primaryShadow | 主要按钮阴影 | string | 0 2px 0 rgba(5,145,255,0.1) |
| solidTextColor | 默认实心按钮的文本色 | string | #fff |
| textHoverBg | 文本按钮悬浮态背景色 | string | rgba(0,0,0,0.04) |
| textTextActiveColor | 默认文本按钮激活态文字颜色 | string | rgba(0,0,0,0.88) |
| textTextColor | 默认文本按钮的文本色 | string | rgba(0,0,0,0.88) |
| textTextHoverColor | 默认文本按钮悬浮态文本颜色 | string | rgba(0,0,0,0.88) |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgSolid | 实心的背景颜色,目前只用在默认实心按钮背景色上。 | string | |
| colorBgSolidActive | 实心的背景颜色激活态,目前只用在默认实心按钮的 active 效果。 | string | |
| colorBgSolidHover | 实心的背景颜色悬浮态,目前只用在默认实心按钮的 hover 效果。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorActive | 错误色的深色激活态 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBgActive | 错误色的浅色背景色激活态 | string | |
| colorErrorBgFilledHover | 错误色的浅色填充背景色悬浮态,目前只用在危险填充按钮的 hover 效果。 | string | |
| colorErrorHover | 错误色的深色悬浮态 | string | |
| colorFill | 最深的填充色,用于拉开与二、三级填充色的区分度,目前只用在 Slider 的 hover 效果。 | string | |
| colorFillSecondary | 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 | string | |
| colorFillTertiary | 三级填充色用于勾勒出元素形体的场景,如 Slider、Segmented 等。如无强调需求的情况下,建议使用三级填色作为默认填色。 | string | |
| colorLink | 控制超链接的颜色。 | string | |
| colorLinkActive | 控制超链接被点击时的颜色。 | string | |
| colorLinkHover | 控制超链接悬浮时的颜色。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryActive | 主色梯度下的深色激活态。 | string | |
| colorPrimaryBg | 主色浅色背景颜色,一般用于视觉层级较弱的选中状态。 | string | |
| colorPrimaryBgHover | 与主色浅色背景颜色相对应的悬浮态颜色。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| opacityLoading | 控制加载状态的透明度。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
## FAQ
### 类型和颜色与变体如何选择? {#faq-type-color-variant}
类型本质上是颜色与变体的语法糖,内部为其提供了一组颜色与变体的映射关系。如果两者同时存在,优先使用颜色与变体。
```jsx
click
```
等同于
```jsx
click
```
### 如何关闭点击波纹效果? {#faq-close-wave-effect}
如果你不需要这个特性,可以设置 [ConfigProvider](/components/config-provider-cn#api) 的 `wave` 的 `disabled` 为 `true`。
```jsx
click
```
## 设计指引 {#design-guide}
- [我的按钮究竟该放哪儿!?| Ant Design 4.0 系列分享](https://zhuanlan.zhihu.com/p/109644406)
---
## calendar-cn
Source: https://ant.design/components/calendar-cn.md
---
category: Components
group: 数据展示
title: Calendar
subtitle: 日历
description: 按照日历形式展示数据的容器。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*nF6_To7pDSAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-p-wQLik200AAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
当数据是日期或按照日期划分时,例如日程、课表、价格日历等,农历等。目前支持年/月切换。
## 代码演示 {#examples}
### 基本
一个通用的日历面板,支持年/月切换。
```tsx
import React from 'react';
import { Calendar } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
const App: React.FC = () => {
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
};
return ;
};
export default App;
```
### 通知事项日历
一个复杂的应用示例,用 `dateCellRender` 和 `monthCellRender` 函数来自定义需要渲染的数据。
```tsx
import React from 'react';
import type { BadgeProps, CalendarProps } from 'antd';
import { Badge, Calendar } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
const useStyles = createStyles((props) => {
const { prefixCls, css } = props;
return {
events: css`
margin: 0;
padding: 0;
list-style: none;
.${prefixCls}-badge-status {
width: 100%;
overflow: hidden;
font-size: 12px;
white-space: nowrap;
text-overflow: ellipsis;
}
`,
notesMonth: css`
font-size: 28px;
text-align: center;
section {
font-size: 28px;
}
`,
};
});
const getListData = (value: Dayjs) => {
let listData: { type: string; content: string }[] = []; // Specify the type of listData
switch (value.date()) {
case 8:
listData = [
{ type: 'warning', content: 'This is warning event.' },
{ type: 'success', content: 'This is usual event.' },
];
break;
case 10:
listData = [
{ type: 'warning', content: 'This is warning event.' },
{ type: 'success', content: 'This is usual event.' },
{ type: 'error', content: 'This is error event.' },
];
break;
case 15:
listData = [
{ type: 'warning', content: 'This is warning event' },
{ type: 'success', content: 'This is very long usual event......' },
{ type: 'error', content: 'This is error event 1.' },
{ type: 'error', content: 'This is error event 2.' },
{ type: 'error', content: 'This is error event 3.' },
{ type: 'error', content: 'This is error event 4.' },
];
break;
default:
break;
}
return listData || [];
};
const getMonthData = (value: Dayjs) => {
if (value.month() === 8) {
return 1394;
}
return undefined;
};
const App: React.FC = () => {
const { styles } = useStyles();
const monthCellRender = (value: Dayjs) => {
const num = getMonthData(value);
return num ? (
Backlog number
) : null;
};
const dateCellRender = (value: Dayjs) => {
const listData = getListData(value);
return (
{listData.map((item) => (
))}
);
};
const cellRender: CalendarProps['cellRender'] = (current, info) => {
if (info.type === 'date') {
return dateCellRender(current);
}
if (info.type === 'month') {
return monthCellRender(current);
}
return info.originNode;
};
return ;
};
export default App;
```
### 跨日期事件
通过 `cellRender` 渲染跨日期事件范围。示例根据日期判断事件的开始、持续、结束或单日状态,并用连续色条展示。
```tsx
import React from 'react';
import { Calendar, theme } from 'antd';
import type { CalendarProps } from 'antd';
import { createStyles } from 'antd-style';
import { clsx } from 'clsx';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const useStyle = createStyles(({ cssVar, css }) => {
const barRadius = 999;
const {
controlHeight,
marginXXS,
controlHeightSM,
colorTextLightSolid,
fontSizeSM,
paddingXS,
marginXS,
paddingXXS,
} = cssVar;
return {
itemContent: css`
overflow: visible;
`,
cell: css`
min-height: ${controlHeight};
`,
list: css`
display: flex;
flex-direction: column;
gap: ${marginXXS};
margin-top: ${marginXXS};
`,
bar: css`
display: block;
height: calc(${controlHeightSM} - ${marginXXS});
overflow: hidden;
color: ${colorTextLightSolid};
font-size: ${fontSizeSM};
white-space: nowrap;
text-overflow: ellipsis;
`,
barStart: css`
margin-inline-end: calc(-1 * (${paddingXS} + ${marginXS} / 2));
padding-inline-start: calc(${paddingXXS} + ${paddingXXS});
border-start-start-radius: ${barRadius}px;
border-end-start-radius: ${barRadius}px;
`,
barMiddle: css`
margin-inline: calc(-1 * (${paddingXS} + ${marginXS} / 2));
`,
barEnd: css`
margin-inline-start: calc(-1 * (${paddingXS} + ${marginXS} / 2));
border-start-end-radius: ${barRadius}px;
border-end-end-radius: ${barRadius}px;
`,
barSingle: css`
padding-inline-start: calc(${paddingXXS} + ${paddingXXS});
border-radius: ${barRadius}px;
`,
};
});
export interface CalendarEvent {
key: string;
title: string;
start: Dayjs;
end: Dayjs;
color: string;
}
const getEvents = (token: ReturnType['token']): CalendarEvent[] => [
{
key: 'release',
title: 'Release window',
start: dayjs('2026-01-08'),
end: dayjs('2026-01-10'),
color: token.colorPrimary,
},
{
key: 'design-review',
title: 'Design review',
start: dayjs('2026-01-14'),
end: dayjs('2026-01-14'),
color: token.colorSuccess,
},
{
key: 'maintenance',
title: 'Maintenance',
start: dayjs('2026-01-21'),
end: dayjs('2026-01-24'),
color: token.colorWarning,
},
{
key: 'bug-fix',
title: 'Bug fix',
start: dayjs('2026-01-30'),
end: dayjs('2026-01-31'),
color: token.colorError,
},
];
const isInRange = (current: Dayjs, event: CalendarEvent) => {
return !current.isBefore(event.start, 'day') && !current.isAfter(event.end, 'day');
};
const getRangePosition = (current: Dayjs, event: CalendarEvent) => {
const starts = current.isSame(event.start, 'day');
const ends = current.isSame(event.end, 'day');
if (starts && ends) {
return 'single';
}
if (starts) {
return 'start';
}
if (ends) {
return 'end';
}
return 'middle';
};
const App: React.FC = () => {
const { token } = theme.useToken();
const { styles } = useStyle();
const events = React.useMemo(() => getEvents(token), [token]);
const cellRender = React.useCallback['cellRender']>>(
(current, info) => {
if (info.type !== 'date') {
return null;
}
const currentEvents = events.filter((event) => isInRange(current, event));
return (
{currentEvents.map((event) => {
const position = getRangePosition(current, event);
const rangeClassName = {
start: styles.barStart,
middle: styles.barMiddle,
end: styles.barEnd,
single: styles.barSingle,
}[position];
return (
{position === 'start' || position === 'single' ? event.title : null}
);
})}
);
},
[events, styles],
);
return (
);
};
export default App;
```
### 卡片模式
用于嵌套在空间有限的容器中。
```tsx
import React from 'react';
import { Calendar, theme } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
};
const App: React.FC = () => {
const { token } = theme.useToken();
const wrapperStyle: React.CSSProperties = {
width: 300,
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorderSecondary}`,
borderRadius: token.borderRadiusLG,
};
return (
);
};
export default App;
```
### 选择功能
一个通用的日历面板,支持年/月切换。
```tsx
import React, { useState } from 'react';
import { Alert, Calendar } from 'antd';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
const App: React.FC = () => {
const [value, setValue] = useState(() => dayjs('2017-01-25'));
const [selectedValue, setSelectedValue] = useState(() => dayjs('2017-01-25'));
const onSelect = (newValue: Dayjs) => {
setValue(newValue);
setSelectedValue(newValue);
};
const onPanelChange = (newValue: Dayjs) => {
setValue(newValue);
};
return (
<>
>
);
};
export default App;
```
### 农历日历
展示农历、节气等信息。
```tsx
import React from 'react';
import { Calendar, Col, Radio, Row, Select } from 'antd';
import type { CalendarProps } from 'antd';
import { createStyles } from 'antd-style';
import type { DefaultOptionType } from 'antd/es/select';
import { clsx } from 'clsx';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { HolidayUtil, Lunar } from 'lunar-typescript';
const useStyle = createStyles(({ cssVar, token, css, cx }) => {
const lunar = css`
color: ${token.colorTextTertiary};
font-size: ${token.fontSizeSM}px;
`;
const weekend = css`
color: ${token.colorError};
&.gray {
opacity: 0.4;
}
`;
return {
wrapper: css`
width: 450px;
border: ${token.lineWidth}px ${token.lineType} ${token.colorBorderSecondary};
border-radius: ${token.borderRadiusOuter};
padding: 5px;
`,
dateCell: css`
position: relative;
&:before {
content: '';
position: absolute;
inset-inline-start: 0;
inset-inline-end: 0;
top: 0;
bottom: 0;
margin: auto;
max-width: 40px;
max-height: 40px;
background: transparent;
transition: background-color ${cssVar.motionDurationSlow};
border-radius: ${token.borderRadiusOuter}px;
border: ${token.lineWidth}px ${token.lineType} transparent;
box-sizing: border-box;
}
&:hover:before {
background: ${token.controlItemBgHover};
}
`,
today: css`
&:before {
border: ${token.lineWidth}px ${token.lineType} ${token.colorPrimary};
}
`,
text: css`
position: relative;
z-index: 1;
`,
lunar,
current: css`
color: ${token.colorTextLightSolid};
&:before {
background: ${token.colorPrimary};
}
&:hover:before {
background: ${token.colorPrimary};
opacity: 0.8;
}
.${cx(lunar)} {
color: ${token.colorTextLightSolid};
opacity: 0.9;
}
.${cx(weekend)} {
color: ${token.colorTextLightSolid};
}
`,
monthCell: css`
width: 120px;
color: ${token.colorTextBase};
border-radius: ${token.borderRadiusOuter}px;
padding: 5px 0;
&:hover {
background: ${token.controlItemBgHover};
}
`,
monthCellCurrent: css`
color: ${token.colorTextLightSolid};
background: ${token.colorPrimary};
&:hover {
background: ${token.colorPrimary};
opacity: 0.8;
}
`,
weekend,
};
});
const App: React.FC = () => {
const { styles } = useStyle({ test: true });
const [selectDate, setSelectDate] = React.useState(() => dayjs());
const [panelDate, setPanelDate] = React.useState(() => dayjs());
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
setPanelDate(value);
};
const onDateChange: CalendarProps['onSelect'] = (value) => {
setSelectDate(value);
};
const cellRender: CalendarProps['fullCellRender'] = (date, info) => {
const d = Lunar.fromDate(date.toDate());
const lunar = d.getDayInChinese();
const solarTerm = d.getJieQi();
const isWeekend = date.day() === 6 || date.day() === 0;
const h = HolidayUtil.getHoliday(date.get('year'), date.get('month') + 1, date.get('date'));
const displayHoliday = h?.getTarget() === h?.getDay() ? h?.getName() : undefined;
if (info.type === 'date') {
return React.cloneElement(info.originNode, {
...(info.originNode as React.ReactElement).props,
className: clsx(styles.dateCell, {
[styles.current]: selectDate.isSame(date, 'date'),
[styles.today]: date.isSame(dayjs(), 'date'),
}),
children: (
{date.get('date')}
{info.type === 'date' && (
{displayHoliday || solarTerm || lunar}
)}
),
});
}
if (info.type === 'month') {
// Due to the fact that a solar month is part of the lunar month X and part of the lunar month X+1,
// when rendering a month, always take X as the lunar month of the month
const d2 = Lunar.fromDate(new Date(date.get('year'), date.get('month')));
const month = d2.getMonthInChinese();
return (
{date.get('month') + 1}月({month}月)
);
}
};
const getYearLabel = (year: number) => {
const d = Lunar.fromDate(new Date(year + 1, 0));
return `${d.getYearInChinese()}年(${d.getYearInGanZhi()}${d.getYearShengXiao()}年)`;
};
const getMonthLabel = (month: number, value: Dayjs) => {
const d = Lunar.fromDate(new Date(value.year(), month));
const lunar = d.getMonthInChinese();
return `${month + 1}月(${lunar}月)`;
};
return (
{
const start = 0;
const end = 12;
const monthOptions: DefaultOptionType[] = [];
let current = value.clone();
const localeData = value.localeData();
const months: dayjs.MonthNames[] = [];
for (let i = 0; i < 12; i++) {
current = current.month(i);
months.push(localeData.monthsShort(current));
}
for (let i = start; i < end; i++) {
monthOptions.push({
label: getMonthLabel(i, value),
value: i,
});
}
const year = value.year();
const month = value.month();
const options: DefaultOptionType[] = [];
for (let i = year - 10; i < year + 10; i += 1) {
options.push({
label: getYearLabel(i),
value: i,
});
}
return (
{
const now = value.clone().year(newYear);
onChange(now);
}}
/>
{
const now = value.clone().month(newMonth);
onChange(now);
}}
/>
onTypeChange(e.target.value)}
value={type}
>
月
年
);
}}
/>
);
};
export default App;
```
### 周数
通过将 `showWeek` 属性设置为 `true`,在全屏日历中显示周数。
```tsx
import React from 'react';
import { Calendar } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 自定义头部
自定义日历头部内容。
```tsx
import React from 'react';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { Calendar, Flex, Radio, Select, theme, Typography } from 'antd';
import type { CalendarProps } from 'antd';
import type { Dayjs } from 'dayjs';
import dayLocaleData from 'dayjs/plugin/localeData';
dayjs.extend(dayLocaleData);
const App: React.FC = () => {
const { token } = theme.useToken();
const onPanelChange = (value: Dayjs, mode: CalendarProps['mode']) => {
console.log(value.format('YYYY-MM-DD'), mode);
};
const wrapperStyle: React.CSSProperties = {
width: 300,
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorderSecondary}`,
borderRadius: token.borderRadiusLG,
};
return (
{
const year = value.year();
const month = value.month();
const yearOptions = Array.from({ length: 20 }, (_, i) => {
const label = year - 10 + i;
return { label, value: label };
});
const monthOptions = value
.localeData()
.monthsShort()
.map((label, index) => ({
label,
value: index,
}));
return (
Custom header
onTypeChange(e.target.value)}
value={type}
>
Month
Year
{
const now = value.clone().year(newYear);
onChange(now);
}}
/>
{
const now = value.clone().month(newMonth);
onChange(now);
}}
/>
);
}}
onPanelChange={onPanelChange}
/>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Calendar 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Calendar, Flex } from 'antd';
import type { CalendarProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
const useStyles = createStyles(({ token }) => ({
root: {
padding: 10,
backgroundColor: token.colorPrimaryBg,
},
}));
const stylesObject: CalendarProps['styles'] = {
root: {
borderRadius: 8,
width: 600,
},
};
const stylesFunction: CalendarProps['styles'] = (
info,
): GetProp, 'styles', 'Return'> => {
if (info.props.fullscreen) {
return {
root: {
border: '2px solid #BDE3C3',
borderRadius: 10,
backgroundColor: 'rgba(189,227,195, 0.3)',
},
};
}
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
**注意**:Calendar 部分 locale 是从 value 中读取,所以请先正确设置 dayjs 的 locale。
```jsx
// 默认语言为 en-US,所以如果需要使用其他语言,推荐在入口文件全局设置 locale
// import dayjs from 'dayjs';
// import 'dayjs/locale/zh-cn';
// dayjs.locale('zh-cn');
```
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| cellRender | 自定义单元格的内容 | function(current: dayjs, info: { prefixCls: string, originNode: React.ReactElement, today: dayjs, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| ~~dateFullCellRender~~ | 自定义渲染日期单元格,返回内容覆盖单元格,>= 5.4.0 请用 `fullCellRender` | function(date: Dayjs): ReactNode | - | < 5.4.0 | × |
| fullCellRender | 自定义单元格的内容 | function(current: dayjs, info: { prefixCls: string, originNode: React.ReactElement, today: dayjs, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| defaultValue | 默认展示的日期 | [dayjs](https://day.js.org/) | - | | × |
| disabledDate | 不可选择的日期,参数为当前 `value`,注意使用时[不要直接修改](https://github.com/ant-design/ant-design/issues/30987) | (currentDate: Dayjs) => boolean | - | | × |
| fullscreen | 是否全屏显示 | boolean | true | | × |
| showWeek | 是否显示周数列 | boolean | false | 5.23.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| headerRender | 自定义头部内容 | function(object:{value: Dayjs, type: 'year' \| 'month', onChange: f(), onTypeChange: f()}) | - | | × |
| locale | 国际化配置 | object | [(默认配置)](https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json) | | × |
| mode | 初始模式 | `month` \| `year` | `month` | | × |
| validRange | 设置可以显示的日期 | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | | × |
| value | 展示日期 | [dayjs](https://day.js.org/) | - | | × |
| onChange | 日期变化回调 | function(date: Dayjs) | - | | × |
| onPanelChange | 日期面板变化回调 | function(date: Dayjs, mode: string) | - | | × |
| onSelect | 选择日期回调,包含来源信息 | function(date: Dayjs, info: { source: 'year' \| 'month' \| 'date' \| 'customize' }) | - | `info`: 5.6.0 | × |
## Semantic DOM
https://ant.design/components/calendar-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Calendar)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| fullBg | 完整日历背景色 | string | #ffffff |
| fullPanelBg | 完整日历面板背景色 | string | #ffffff |
| itemActiveBg | 日期项选中背景色 | string | #e6f4ff |
| miniContentHeight | 迷你日历内容高度 | string \| number | 256 |
| monthControlWidth | 月选择器宽度 | string \| number | 70 |
| yearControlWidth | 年选择器宽度 | string \| number | 80 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorFillSecondary | 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextTertiary | 第三级文本色一般用于描述性文本,例如表单的中的补充说明文本、列表的描述性文本等场景。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| controlItemBgActive | 控制组件项在激活状态下的背景颜色。 | string | |
| controlItemBgHover | 控制组件项在鼠标悬浮时的背景颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingSM | 控制元素的小内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
| screenXS | 控制超小屏幕的屏幕宽度。 | number | |
## FAQ
### 如何在 Calendar 中使用自定义日期库 {#faq-customize-date-library}
参考 [使用自定义日期库](/docs/react/use-custom-date-library#calendar)。
### 如何给日期类组件配置国际化? {#faq-set-locale-date-components}
参考 [如何给日期类组件配置国际化](/components/date-picker-cn#%E5%9B%BD%E9%99%85%E5%8C%96%E9%85%8D%E7%BD%AE)。
### 为什么时间类组件的国际化 locale 设置不生效? {#faq-locale-not-working}
参考 FAQ [为什么时间类组件的国际化 locale 设置不生效?](/docs/react/faq#为什么时间类组件的国际化-locale-设置不生效)。
### 如何仅获取来自面板点击的日期? {#faq-get-date-panel-click}
`onSelect` 事件提供额外的来源信息,你可以通过 `info.source` 来判断来源:
```tsx
{
if (source === 'date') {
console.log('Panel Select:', source);
}
}}
/>
```
---
## card-cn
Source: https://ant.design/components/card-cn.md
---
category: Components
group: 数据展示
title: Card
subtitle: 卡片
description: 通用卡片容器。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*QXO1SKEdIzYAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*5WDvQp_H7LUAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
最基础的卡片容器,可承载文字、列表、图片、段落,常用于后台概览页面。
## 代码演示 {#examples}
### 典型卡片
包含标题、内容、操作区域。
```tsx
import React from 'react';
import { Card, Space } from 'antd';
const App: React.FC = () => (
More} style={{ width: 300 }}>
Card content
Card content
Card content
More} style={{ width: 300 }}>
Card content
Card content
Card content
);
export default App;
```
### 无边框
在灰色背景上使用无边框的卡片。
```tsx
import React from 'react';
import { Card } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
);
export default App;
```
### 简洁卡片
只包含内容区域。
```tsx
import React from 'react';
import { Card } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
);
export default App;
```
### 更灵活的内容展示
可以利用 `Card.Meta` 支持更灵活的内容。
```tsx
import React from 'react';
import { Card } from 'antd';
const { Meta } = Card;
const App: React.FC = () => (
}
>
);
export default App;
```
### 栅格卡片
在系统概览页面常常和栅格进行配合。
```tsx
import React from 'react';
import { Card, Col, Row } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
);
export default App;
```
### 预加载的卡片
数据读入前会有文本块样式。
```tsx
import React, { useState } from 'react';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Card, Flex, Switch } from 'antd';
const actions: React.ReactNode[] = [
,
,
,
];
const App: React.FC = () => {
const [loading, setLoading] = useState(true);
return (
setLoading(!checked)} />
}
title="Card title"
description={
<>
This is the description
This is the description
>
}
/>
}
title="Card title"
description={
<>
This is the description
This is the description
>
}
/>
);
};
export default App;
```
### 网格型内嵌卡片
一种常见的卡片内容区隔模式。
```tsx
import React from 'react';
import { Card } from 'antd';
const gridStyle: React.CSSProperties = {
width: '25%',
textAlign: 'center',
};
const App: React.FC = () => (
Content
Content
Content
Content
Content
Content
Content
);
export default App;
```
### 内部卡片
可以放在普通卡片内部,展示多层级结构的信息。
```tsx
import React from 'react';
import { Card } from 'antd';
const App: React.FC = () => (
More}>
Inner Card content
More}
>
Inner Card content
);
export default App;
```
### 带页签的卡片
可承载更多内容。
```tsx
import React, { useState } from 'react';
import { Card } from 'antd';
const tabList = [
{
key: 'tab1',
tab: 'tab1',
},
{
key: 'tab2',
tab: 'tab2',
},
];
const contentList: Record = {
tab1: content1
,
tab2: content2
,
};
const tabListNoTitle = [
{
key: 'article',
label: 'article',
},
{
key: 'app',
label: 'app',
},
{
key: 'project',
label: 'project',
},
];
const contentListNoTitle: Record = {
article: article content
,
app: app content
,
project: project content
,
};
const App: React.FC = () => {
const [activeTabKey1, setActiveTabKey1] = useState('tab1');
const [activeTabKey2, setActiveTabKey2] = useState('app');
const onTab1Change = (key: string) => {
setActiveTabKey1(key);
};
const onTab2Change = (key: string) => {
setActiveTabKey2(key);
};
return (
<>
More}
tabList={tabList}
activeTabKey={activeTabKey1}
onTabChange={onTab1Change}
>
{contentList[activeTabKey1]}
More}
onTabChange={onTab2Change}
tabProps={{ size: 'medium' }}
>
{contentListNoTitle[activeTabKey2]}
>
);
};
export default App;
```
### 支持更多内容配置
一种支持封面、头像、标题和描述信息的卡片。
```tsx
import React from 'react';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Card } from 'antd';
const { Meta } = Card;
const App: React.FC = () => (
}
actions={[
,
,
,
]}
>
}
title="Card title"
description="This is the description"
/>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Card 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { EditOutlined, HeartOutlined, ShareAltOutlined } from '@ant-design/icons';
import { Avatar, Button, Card, Flex } from 'antd';
import type { CardMetaProps, CardProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const { Meta } = Card;
const useStyles = createStyles(({ token }) => ({
root: {
width: 300,
backgroundColor: token.colorBgContainer,
borderRadius: token.borderRadius,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorderSecondary}`,
},
header: {
borderBottom: 'none',
paddingBottom: token.paddingXS,
},
body: {
paddingTop: 0,
},
}));
const stylesCard: CardProps['styles'] = {
root: {
boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
borderRadius: 8,
},
title: {
fontSize: 16,
fontWeight: 500,
},
};
const stylesCardFn: CardProps['styles'] = (info): GetProp => {
if (info.props.variant === 'outlined') {
return {
root: {
borderColor: '#696FC7',
boxShadow: '0 2px 8px #A7AAE1',
borderRadius: 8,
},
extra: {
color: '#696FC7',
},
title: {
fontSize: 16,
fontWeight: 500,
color: '#A7AAE1',
},
};
}
};
const stylesCardMeta: CardMetaProps['styles'] = {
title: {
color: '#A7AAE1',
},
description: {
color: '#A7AAE1',
},
};
const actions = [
,
,
,
];
const App: React.FC = () => {
const { styles: classNames } = useStyles();
const sharedCardProps: CardProps = {
classNames,
actions,
};
const sharedCardMetaProps: CardMetaProps = {
avatar: ,
description: 'This is the description',
};
return (
More}
variant="borderless"
>
More
}
>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
```jsx
卡片内容
```
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| actions | 卡片操作组,位置在卡片底部 | Array<ReactNode> | - | | × |
| activeTabKey | 当前激活页签的 key | string | - | | × |
| ~~bordered~~ | 是否有边框, 请使用 `variant` 替换 | boolean | true | | × |
| ~~bodyStyle~~ | 卡片内容区域样式,请使用 `styles.body` 替代 | CSSProperties | - | - | × |
| variant | 形态变体 | `outlined` \| `borderless` | `outlined` | 5.24.0 | 5.24.0 |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.14.0 |
| cover | 卡片封面 | ReactNode | - | | × |
| defaultActiveTabKey | 初始化选中页签的 key,如果没有设置 activeTabKey | string | `第一个页签的 key` | | × |
| extra | 卡片右上角的操作区域 | ReactNode | - | | × |
| hoverable | 鼠标移过时可浮起 | boolean | false | | × |
| ~~headStyle~~ | 卡片头部样式,请使用 `styles.header` 替代 | CSSProperties | - | - | × |
| loading | 当卡片内容还在加载中时,可以用 loading 展示一个占位 | boolean | false | | × |
| size | card 的尺寸 | `medium` \| `small` | `medium` | | × |
| tabBarExtraContent | tab bar 上额外的元素 | ReactNode | - | | × |
| tabList | 页签标题列表 | [TabItemType](/components/tabs-cn#tabitemtype)[] | - | | × |
| tabProps | [Tabs](/components/tabs-cn#tabs) | - | - | | × |
| title | 卡片标题 | ReactNode | - | | × |
| type | 卡片类型,可设置为 `inner` 或 不设置 | string | - | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.14.0 |
| onTabChange | 页签切换的回调 | (key) => void | - | | × |
### Card.Grid
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------- | ---------------- | ------- | ------ | ---- |
| hoverable | 鼠标移过时可浮起 | boolean | true | |
### Card.Meta
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| avatar | 头像/图标 | ReactNode | - | | × |
| description | 描述内容 | ReactNode | - | | × |
| title | 标题内容 | ReactNode | - | | × |
## Semantic DOM
### Card
https://ant.design/components/card-cn/semantic.md
### Card.Meta
https://ant.design/components/card-cn/semantic_meta.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Card)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| actionsBg | 操作区背景色 | string | #ffffff |
| actionsLiMargin | 操作区每一项的外间距 | string | 12px 0 |
| bodyPadding | 卡片内边距 | number | 24 |
| bodyPaddingSM | 小号卡片内边距 | number | 12 |
| extraColor | 额外区文字颜色 | string | rgba(0,0,0,0.88) |
| headerBg | 卡片头部背景色 | string | transparent |
| headerFontSize | 卡片头部文字大小 | string \| number | 16 |
| headerFontSizeSM | 小号卡片头部文字大小 | string \| number | 14 |
| headerHeight | 卡片头部高度 | string \| number | 56 |
| headerHeightSM | 小号卡片头部高度 | string \| number | 38 |
| headerPadding | 卡片头部内边距 | number | 24 |
| headerPaddingSM | 小号卡片头部内边距 | number | 12 |
| tabsMarginBottom | 内置标签页组件下间距 | number | -17 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| boxShadowTertiary | 控制元素三级盒子阴影样式。 | string | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBorderSecondary | 比默认使用的边框色要浅一级,此颜色和 colorSplit 的颜色一致。使用的是实色。 | string | |
| colorFillAlter | 控制元素替代背景色。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
---
## carousel-cn
Source: https://ant.design/components/carousel-cn.md
---
category: Components
group: 数据展示
title: Carousel
subtitle: 走马灯
description: 一组轮播的区域。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*bPMSSqbaTMkAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*a-58QpYnqOsAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 当有一组平级的内容。
- 当内容空间不足时,可以用走马灯的形式进行收纳,进行轮播展现。
- 常用于一组图片或卡片轮播。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => {
const onChange = (currentSlide: number) => {
console.log(currentSlide);
};
return (
1
2
3
4
);
};
export default App;
```
### 位置
位置有 4 个方向。
```tsx
import React, { useState } from 'react';
import type { CarouselProps, RadioChangeEvent } from 'antd';
import { Carousel, Radio } from 'antd';
type DotPlacement = CarouselProps['dotPlacement'];
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => {
const [dotPlacement, setDotPlacement] = useState('top');
const handlePositionChange = ({ target: { value } }: RadioChangeEvent) => {
setDotPlacement(value);
};
return (
<>
Top
Bottom
Start
End
1
2
3
4
>
);
};
export default App;
```
### 自动切换
定时切换下一张。
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
1
2
3
4
);
export default App;
```
### 渐显
切换效果为渐显。
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
1
2
3
4
);
export default App;
```
### 切换箭头
显示切换箭头。
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
<>
1
2
3
4
1
2
3
4
>
);
export default App;
```
### 进度条
展示指示点的进度。
```tsx
import React from 'react';
import { Carousel } from 'antd';
const contentStyle: React.CSSProperties = {
margin: 0,
height: '160px',
color: '#fff',
lineHeight: '160px',
textAlign: 'center',
background: '#364d79',
};
const App: React.FC = () => (
1
2
3
4
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| arrows | 是否显示箭头 | boolean | false | 5.17.0 | × |
| autoplay | 是否自动切换,如果为 object 可以指定 `dotDuration` 来展示指示点进度条 | boolean \| { dotDuration?: boolean } | false | dotDuration: 5.24.0 | × |
| autoplaySpeed | 自动切换的间隔(毫秒) | number | 3000 | | × |
| adaptiveHeight | 高度自适应 | boolean | false | | × |
| dotPlacement | 面板指示点位置,可选 `top` `bottom` `start` `end` | string | `bottom` | | × |
| ~~dotPosition~~ | 面板指示点位置,可选 `top` `bottom` `left` `right` `start` `end`,请使用 `dotPlacement` 替换 | string | `bottom` | | × |
| dots | 是否显示面板指示点,如果为 `object` 则可以指定 `dotsClass` | boolean \| { className?: string } | true | | × |
| draggable | 是否启用拖拽切换 | boolean | false | | × |
| fade | 使用渐变切换动效 | boolean | false | | × |
| infinite | 是否无限循环切换(实现方式是复制两份 children 元素,如果子元素有副作用则可能会引发 bug) | boolean | true | | × |
| speed | 切换动效的时间(毫秒) | number | 500 | | × |
| easing | 动画效果 | string | `linear` | | × |
| effect | 动画效果函数 | `scrollx` \| `fade` | `scrollx` | | × |
| afterChange | 切换面板的回调 | (current: number) => void | - | | × |
| beforeChange | 切换面板的回调 | (current: number, next: number) => void | - | | × |
| waitForAnimate | 是否等待切换动画 | boolean | false | | × |
更多 API 可参考:
## 方法 {#methods}
| 名称 | 描述 |
| ------------------------------ | ------------------------------------------------- |
| goTo(slideNumber, dontAnimate) | 切换到指定面板, dontAnimate = true 时,不使用动画 |
| next() | 切换到下一面板 |
| prev() | 切换到上一面板 |
## 主题变量(Design Token){#design-token}
## 组件 Token (Carousel)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| arrowOffset | 切换箭头边距 | number | 8 |
| arrowSize | 切换箭头大小 | number | 16 |
| dotActiveWidth | 激活态指示点宽度 | string \| number | 24 |
| dotGap | 指示点之间的间距 | number | 4 |
| dotHeight | 指示点高度 | string \| number | 3 |
| dotOffset | 指示点距离边缘的距离 | number | 12 |
| dotWidth | 指示点宽度 | string \| number | 16 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
## FAQ
### 如何自定义箭头? {#faq-add-custom-arrows}
可参考 [#12479](https://github.com/ant-design/ant-design/issues/12479)。
---
## cascader-cn
Source: https://ant.design/components/cascader-cn.md
---
category: Components
group: 数据录入
title: Cascader
subtitle: 级联选择
description: 级联选择框。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ngTnQZNOcK0AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Nt8xR7afyr0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 需要从一组相关联的数据集合进行选择,例如省市区,公司层级,事物分类等。
- 从一个较大的数据集合中进行选择时,用多级分类进行分隔,方便选择。
- 比起 Select 组件,可以在同一个浮层中完成选择,有较好的体验。
## 代码演示 {#examples}
### 基本
省市区级联。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
import type { HTMLAriaDataAttributes } from 'antd/es/_util/aria-data-attrs';
type Option = {
value: string;
label: string;
children?: Option[];
} & HTMLAriaDataAttributes;
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
'aria-label': 'Zhejiang',
'data-title': 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
'aria-label': 'Hangzhou',
'data-title': 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
'aria-label': 'West Lake',
'data-title': 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
'aria-label': 'Jiangsu',
'data-title': 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
'aria-label': 'Nanjing',
'data-title': 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
'aria-label': 'Zhong Hua Men',
'data-title': 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### 默认值
默认值通过数组的方式指定。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### 可以自定义显示
切换按钮和结果分开。
```tsx
import React, { useState } from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
},
],
},
];
const App: React.FC = () => {
const [text, setText] = useState('Unselect');
const onChange: CascaderProps ['onChange'] = (_, selectedOptions) => {
setText(selectedOptions.map((o) => o.label).join(', '));
};
return (
{text}
Change city
);
};
export default App;
```
### 移入展开
通过移入展开下级菜单,点击完成选择。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
// Just show the latest item.
const displayRender = (labels: string[]) => labels[labels.length - 1];
const App: React.FC = () => (
);
export default App;
```
### 禁用选项
通过指定 options 里的 `disabled` 字段。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
disabled?: boolean;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
disabled: true,
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => ;
export default App;
```
### 选择即改变
这种交互允许只选中父级选项。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hanzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => ;
export default App;
```
### 多选
一次性选择多个选项。通过添加 `disableCheckbox` 属性,选择具体某一个`checkbox`禁用 。可以通过类名修改禁用的样式。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string | number;
label: string;
children?: Option[];
disableCheckbox?: boolean;
}
const options: Option[] = [
{
label: 'Light',
value: 'light',
children: Array.from({ length: 20 }).map((_, index) => ({
label: `Number ${index}`,
value: index,
})),
},
{
label: 'Bamboo',
value: 'bamboo',
children: [
{
label: 'Little',
value: 'little',
children: [
{
label: 'Toy Fish',
value: 'fish',
disableCheckbox: true,
},
{
label: 'Toy Cards',
value: 'cards',
},
{
label: 'Toy Bird',
value: 'bird',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### 自定义回填方式
通过设置 `showCheckedStrategy` 选择回填方式。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
const { SHOW_CHILD } = Cascader;
interface Option {
value: string | number;
label: string;
children?: Option[];
}
const options: Option[] = [
{
label: 'Light',
value: 'light',
children: Array.from({ length: 20 }).map((_, index) => ({
label: `Number ${index}`,
value: index,
})),
},
{
label: 'Bamboo',
value: 'bamboo',
children: [
{
label: 'Little',
value: 'little',
children: [
{
label: 'Toy Fish',
value: 'fish',
},
{
label: 'Toy Cards',
value: 'cards',
},
{
label: 'Toy Bird',
value: 'bird',
},
],
},
],
},
];
const App: React.FC = () => {
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
return (
<>
>
);
};
export default App;
```
### 大小
不同大小的级联选择器。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### 自定义已选项
例如给最后一项加上邮编链接。
```tsx
import React from 'react';
import { Cascader } from 'antd';
import type { CascaderProps, GetProp } from 'antd';
type DefaultOptionType = GetProp[number];
interface Option {
value: string;
label: string;
children?: Option[];
code?: number;
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
code: 752100,
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
code: 453400,
},
],
},
],
},
];
const handleAreaClick = (
e: React.MouseEvent,
label: string,
option: DefaultOptionType,
) => {
e.stopPropagation();
console.log('clicked', label, option);
};
const displayRender: CascaderProps['displayRender'] = (labels, selectedOptions = []) =>
labels.map((label, i) => {
const option = selectedOptions[i];
if (i === labels.length - 1) {
return (
{label} ( handleAreaClick(e, label, option)}>{option.code} )
);
}
return {label} / ;
});
const App: React.FC = () => (
(
<>
{option.label} ({option.value})
>
)}
/>
);
export default App;
```
### 搜索
可以直接搜索选项并选择。
> `Cascader[showSearch]` 暂不支持服务端搜索,更多信息见 [#5547](https://github.com/ant-design/ant-design/issues/5547)
```tsx
import React from 'react';
import { Cascader } from 'antd';
import type { CascaderProps, GetProp } from 'antd';
type DefaultOptionType = GetProp[number];
interface Option {
value: string;
label: string;
children?: Option[];
disabled?: boolean;
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
{
value: 'xiasha',
label: 'Xia Sha',
disabled: true,
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua men',
},
],
},
],
},
];
const onChange: CascaderProps['onChange'] = (value, selectedOptions) => {
console.log(value, selectedOptions);
};
const filter = (inputValue: string, path: DefaultOptionType[]) =>
path.some((option) => (option.label as string).toLowerCase().includes(inputValue.toLowerCase()));
const App: React.FC = () => (
console.log(value) }}
/>
);
export default App;
```
### 动态加载选项
使用 `loadData` 实现动态加载选项。
> 注意:`loadData` 与 `showSearch` 无法一起使用。
```tsx
import React, { useState } from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value?: string | number | null;
label: React.ReactNode;
children?: Option[];
isLeaf?: boolean;
}
const optionLists: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
isLeaf: false,
},
{
value: 'jiangsu',
label: 'Jiangsu',
isLeaf: false,
},
];
const App: React.FC = () => {
const [options, setOptions] = useState(optionLists);
const onChange: CascaderProps ['onChange'] = (value, selectedOptions) => {
console.log(value, selectedOptions);
};
const loadData = (selectedOptions: Option[]) => {
const targetOption = selectedOptions[selectedOptions.length - 1];
// load options lazily
setTimeout(() => {
targetOption.children = [
{
label: `${targetOption.label} Dynamic 1`,
value: 'dynamic1',
},
{
label: `${targetOption.label} Dynamic 2`,
value: 'dynamic2',
},
];
setOptions([...options]);
}, 1000);
};
return ;
};
export default App;
```
### 自定义字段名
自定义字段名。
```tsx
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
code: string;
name: string;
items?: Option[];
}
const options: Option[] = [
{
code: 'zhejiang',
name: 'Zhejiang',
items: [
{
code: 'hangzhou',
name: 'Hangzhou',
items: [
{
code: 'xihu',
name: 'West Lake',
},
],
},
],
},
{
code: 'jiangsu',
name: 'Jiangsu',
items: [
{
code: 'nanjing',
name: 'Nanjing',
items: [
{
code: 'zhonghuamen',
name: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
);
export default App;
```
### 前后缀
通过 `prefix` 自定前缀,通过 `suffixIcon` 自定义选择框后缀图标,通过 `expandIcon` 自定义次级菜单展开图标。
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => (
<>
}
options={options}
onChange={onChange}
placeholder="Please select"
/>
}
options={options}
onChange={onChange}
placeholder="Please select"
/>
}
options={options}
onChange={onChange}
placeholder="Please select"
/>
>
);
export default App;
```
### 扩展菜单
使用 `popupRender` 对下拉菜单进行自由扩展。
```tsx
import React from 'react';
import { Cascader, Divider } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const popupRender = (menus: React.ReactNode) => (
{menus}
The footer is not very short.
);
const App: React.FC = () => (
);
export default App;
```
### 弹出位置
可以通过 `placement` 手动指定弹出的位置。
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Cascader, Radio } from 'antd';
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const App: React.FC = () => {
const [placement, setPlacement] = useState<'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight'>(
'topLeft',
);
const placementChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
topLeft
topRight
bottomLeft
bottomRight
>
);
};
export default App;
```
### 形态变体
Cascader 形态变体,可选 `outlined` `filled` `borderless` `underlined` 四种形态。
```tsx
import React from 'react';
import { Cascader, Flex } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义状态
使用 `status` 为 Cascader 添加状态,可选 `error` 或者 `warning`。
```tsx
import React from 'react';
import { Cascader, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Cascader 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Cascader, Flex } from 'antd';
import type { CascaderProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => {
return {
root: {
borderRadius: token.borderRadiusLG,
},
};
});
interface Option {
value: string;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'meet-student',
label: 'meet-student',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const stylesObject: CascaderProps['styles'] = {
prefix: {
color: '#ccc',
},
suffix: {
color: '#ccc',
},
};
const stylesFn: CascaderProps['styles'] = (info): GetProp => {
if (info.props.variant === 'filled') {
return {
prefix: {
color: '#1890ff',
},
suffix: {
color: '#1890ff',
},
popup: {
listItem: {
color: '#1890ff',
},
},
};
}
return {};
};
const onChange: CascaderProps['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
### = 5.10.0">面板使用
适用于一些需要内嵌适用的场景。
```tsx
import React, { useState } from 'react';
import type { CascaderProps } from 'antd';
import { Cascader, Flex, Switch } from 'antd';
interface Option {
value: string | number;
label: string;
children?: Option[];
}
const options: Option[] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const onChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const onMultipleChange: CascaderProps ['onChange'] = (value) => {
console.log(value);
};
const App: React.FC = () => {
const [disabled, setDisabled] = useState(false);
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
```jsx
```
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | 支持清除 | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: 支持对象形式 | `clearIcon`: 6.4.0 |
| ~~autoClearSearchValue~~ | 是否在选中项后清空搜索框,只在 `multiple` 为 `true` 时有效 | boolean | true | 5.9.0 | × |
| ~~bordered~~ | 是否带边框,请使用 `variant` 替代 | boolean | true | - | × |
| changeOnSelect | 单选时生效(multiple 下始终都可以选择),点选每级菜单选项值都会发生变化。 | boolean | false | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.25.0 |
| defaultOpen | 是否默认展示浮层 | boolean | - | | × |
| defaultValue | 默认的选中项 | string\[] \| number\[] | \[] | | × |
| disabled | 禁用 | boolean | false | | × |
| displayRender | 选择后展示的渲染函数 | (label, selectedOptions) => ReactNode | label => label.join(`/`) | `multiple`: 4.18.0 | × |
| tagRender | 自定义 tag 内容 render,仅在多选时生效 | ({ label: string, onClose: function, value: string }) => ReactNode | - | | × |
| ~~popupClassName~~ | 自定义浮层类名,使用 `classNames.popup.root` 替换 | string | - | 4.23.0 | × |
| ~~dropdownClassName~~ | 自定义浮层类名,请使用 `classNames.popup.root` 替代 | string | - | - | × |
| ~~dropdownRender~~ | 自定义下拉框内容,请使用 `popupRender` 替换 | (menus: ReactNode) => ReactNode | - | 4.4.0 | × |
| popupRender | 自定义下拉框内容 | (menus: ReactNode) => ReactNode | - | | × |
| ~~dropdownStyle~~ | 下拉菜单的 style 属性,使用 `styles.popup.root` 替换 | CSSProperties | - | | × |
| expandIcon | 自定义次级菜单展开图标 | ReactNode | - | 4.4.0 | 6.3.0 |
| expandTrigger | 次级菜单的展开方式,可选 'click' 和 'hover' | string | `click` | | × |
| fieldNames | 自定义 options 中 label value children 的字段 | object | { label: `label`, value: `value`, children: `children` } | | × |
| getPopupContainer | 菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。[示例](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | function(triggerNode) | () => document.body | | × |
| loadData | 用于动态加载选项,无法与 `showSearch` 一起使用 | (selectedOptions) => void | - | | × |
| loadingIcon | 自定义的加载图标 | ReactNode | - | | 6.3.0 |
| maxTagCount | 最多显示多少个 tag,响应式模式会对性能产生损耗 | number \| `responsive` | - | 4.17.0 | × |
| maxTagPlaceholder | 隐藏 tag 时显示的内容 | ReactNode \| function(omittedValues) | - | 4.17.0 | × |
| maxTagTextLength | 最大显示的 tag 文本长度 | number | - | 4.17.0 | × |
| notFoundContent | 当下拉列表为空时显示的内容 | ReactNode | `Not Found` | | × |
| open | 控制浮层显隐 | boolean | - | 4.17.0 | × |
| options | 可选项数据源 | [Option](#option)\[] | - | | × |
| placeholder | 输入框占位文本 | string | - | | × |
| placement | 浮层预设位置 | `bottomLeft` `bottomRight` `topLeft` `topRight` | `bottomLeft` | 4.17.0 | × |
| prefix | 自定义前缀 | ReactNode | - | 5.22.0 | × |
| ~~showArrow~~ | 是否显示箭头图标,请使用 `suffixIcon={null}` 替代 | boolean | true | - | × |
| showSearch | 在选择框中显示搜索框 | boolean \| [Object](#showsearch) | false | | `searchIcon`: 6.4.0 |
| size | 输入框大小 | `large` \| `medium` \| `small` | `medium` | | × |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.25.0 |
| suffixIcon | 自定义的选择框后缀图标 | ReactNode | - | | 6.4.0 |
| value | 指定选中项 | string\[] \| number\[] | - | | × |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | 5.19.0 |
| onChange | 选择完成后的回调 | (value, selectedOptions) => void | - | | × |
| onClear | 清除内容时回调 | () => void | - | - | × |
| ~~onDropdownVisibleChange~~ | 显示/隐藏浮层的回调,请使用 `onOpenChange` 替换 | (value) => void | - | 4.17.0 | × |
| onOpenChange | 显示/隐藏浮层的回调 | (value) => void | - | | × |
| ~~onPopupVisibleChange~~ | 显示或隐藏浮层的回调,请使用 `onOpenChange` 替代 | (value) => void | - | - | × |
| multiple | 支持多选节点 | boolean | - | 4.17.0 | × |
| removeIcon | 自定义的多选框清除图标 | ReactNode | - | | 6.4.0 |
| showCheckedStrategy | 定义选中项回填的方式(仅在 `multiple` 为 `true` 时生效)。`Cascader.SHOW_CHILD`: 只显示选中的子节点。`Cascader.SHOW_PARENT`: 只显示父节点(当父节点下所有子节点都选中时)。 | `Cascader.SHOW_PARENT` \| `Cascader.SHOW_CHILD` | `Cascader.SHOW_PARENT` | 4.20.0 | × |
| ~~searchValue~~ | 设置搜索的值,需要与 `showSearch` 配合使用 | string | - | 4.17.0 | × |
| ~~onSearch~~ | 监听搜索,返回输入的值 | (search: string) => void | - | 4.17.0 | × |
| ~~dropdownMenuColumnStyle~~ | 下拉菜单列的样式,请使用 `styles.popup.listItem` 替换 | CSSProperties | - | | × |
| ~~popupMenuColumnStyle~~ | 下拉菜单列的样式,请使用 `styles.popup.listItem` 替换 | CSSProperties | - | | × |
| optionRender | 自定义渲染下拉选项 | (option: Option) => React.ReactNode | - | 5.16.0 | × |
### showSearch
`showSearch` 为对象时,其中的字段:
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| autoClearSearchValue | 是否在选中项后清空搜索框,只在 `multiple` 为 `true` 时有效 | boolean | true | 5.9.0 |
| filter | 接收 `inputValue` `path` 两个参数,当 `path` 符合筛选条件时,应返回 true,反之则返回 false | function(inputValue, path): boolean | - | |
| limit | 搜索结果展示数量 | number \| false | 50 | |
| matchInputWidth | 搜索结果列表是否与输入框同宽([效果](https://github.com/ant-design/ant-design/issues/25779)) | boolean | true | |
| render | 用于渲染 filter 后的选项 | function(inputValue, path): ReactNode | - | |
| sort | 用于排序 filter 后的选项 | function(a, b, inputValue) | - | |
| searchValue | 设置搜索的值,需要与 `showSearch` 配合使用 | string | - | 4.17.0 |
| onSearch | 监听搜索,返回输入的值 | (search: string) => void | - | 4.17.0 |
| searchIcon | 自定义的搜索图标 | ReactNode | - | 6.3.0 |
### Option
```typescript
interface Option {
value: string | number;
label?: React.ReactNode;
disabled?: boolean;
children?: Option[];
// 标记是否为叶子节点,设置了 `loadData` 时有效
// 设为 `false` 时会强制标记为父节点,即使当前节点没有 children,也会显示展开图标
isLeaf?: boolean;
}
```
## 方法 {#methods}
| 名称 | 描述 | 版本 |
| ------- | -------- | ---- |
| blur() | 移除焦点 | |
| focus() | 获取焦点 | |
> 注意,如果需要获得中国省市区数据,可以参考 [china-division](https://gist.github.com/afc163/7582f35654fd03d5be7009444345ea17)。
## Semantic DOM
https://ant.design/components/cascader-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Cascader)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| controlItemWidth | 选项宽度 | string \| number | 111 |
| controlWidth | 选择器宽度 | string \| number | 184 |
| dropdownHeight | 下拉菜单高度 | string \| number | 180 |
| menuPadding | 选项菜单(单列)内间距 | Padding \| undefined | 4 |
| optionPadding | 选项内间距 | Padding \| undefined | 5px 12px |
| optionSelectedBg | 选项选中时背景色 | string | #e6f4ff |
| optionSelectedColor | 选项选中时文本颜色 | string | rgba(0,0,0,0.88) |
| optionSelectedFontWeight | 选项选中时字重 | FontWeight \| undefined | 600 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorHighlight | 控制页面元素高亮时的颜色。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorWhite | 不随主题变化的纯白色 | string | |
| controlInteractiveSize | 控制组件的交互大小。 | number | |
| controlItemBgHover | 控制组件项在鼠标悬浮时的背景颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationFast | 动效播放速度,快速。用于小型元素动画交互 | string | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInBack | 预设动效曲率 | string | |
| motionEaseOutBack | 预设动效曲率 | string | |
| paddingXS | 控制元素的特小内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
---
## changelog-cn
Source: https://ant.design/components/changelog-cn.md
---
order: 6
title: 更新日志
timeline: true
tag: vVERSION
---
`antd` 遵循 [Semantic Versioning 2.0.0](http://semver.org/lang/zh-CN/) 语义化版本规范。
#### 发布周期
- 修订版本号:每周末会进行日常 bugfix 更新。(如果有紧急的 bugfix,则任何时候都可发布)
- 次版本号:每月发布一个带有新特性的向下兼容的版本。
- 主版本号:含有破坏性更新和新特性,不在发布周期内。
---
## 6.6.0
`2026-08-10`
- 🔥 新增 Listy 高性能虚拟列表组件,支持分组、吸顶标题和命令式滚动。[#58724](https://github.com/ant-design/ant-design/pull/58724) [@aojunhao123](https://github.com/aojunhao123)
- ConfigProvider
- 🆕 新增 ConfigProvider 主题 Token `focusOutline`,用于统一控制 Input、Select、Rate、Steps、Splitter 等组件的聚焦描边。[#58647](https://github.com/ant-design/ant-design/pull/58647) [#58708](https://github.com/ant-design/ant-design/pull/58708) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 ConfigProvider 全局配置 Input.Search、Input.Password 和 Input.OTP `variant` 的能力。[#58784](https://github.com/ant-design/ant-design/pull/58784) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 ConfigProvider 对 Tooltip、Popover 和 Popconfirm `mouseEnterDelay` 与 `mouseLeaveDelay` 的全局配置支持。[#58892](https://github.com/ant-design/ant-design/pull/58892) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🌐 国际化
- 🇦🇱 新增阿尔巴尼亚语 `sq_AL` locale 本地化支持。[#58618](https://github.com/ant-design/ant-design/pull/58618) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 新增 Tree `useTree` 以获取节点路径,并支持 `scrollTo({ autoExpand: true })` 在滚动前自动展开目标节点。[#58841](https://github.com/ant-design/ant-design/pull/58841) [@zombieJ](https://github.com/zombieJ)
- 🆕 新增 FloatButton.BackTop `showProgress`,用于在按钮边缘展示当前滚动进度。[#58894](https://github.com/ant-design/ant-design/pull/58894) [@ZQDesigned](https://github.com/ZQDesigned)
- 🆕 新增 Table `expandable.forceRender`,支持在首次展开前渲染展开行内容。[#58860](https://github.com/ant-design/ant-design/pull/58860) [@nikzanda](https://github.com/nikzanda)
- 🆕 新增 Pagination `components.sizeChanger`,支持自定义每页条数切换器,并可用于 Table 分页。[#58831](https://github.com/ant-design/ant-design/pull/58831) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Mentions `popupRender` 属性,支持自定义建议下拉菜单的渲染。[#58582](https://github.com/ant-design/ant-design/pull/58582) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 Tabs `more.popupRender`,支持自定义折叠下拉菜单内容。[#58651](https://github.com/ant-design/ant-design/pull/58651) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 BorderBeam `count` 属性,支持在容器边缘显示多条均匀分布的流光。[#58691](https://github.com/ant-design/ant-design/pull/58691) [@meet-student](https://github.com/meet-student)
- 🆕 新增 Image `preview.wheel` 属性,用于控制预览时是否启用鼠标滚轮缩放。[#58728](https://github.com/ant-design/ant-design/pull/58728) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 Alert `borderRadius` 组件 Token,用于自定义圆角。[#57765](https://github.com/ant-design/ant-design/pull/57765) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Avatar.Group、Badge.Ribbon、Breadcrumb、Calendar、Card.Grid、Card.Meta、Carousel、Descriptions、Divider、Empty、FloatButton.Group、List.Item.Meta、QRCode、Result、Skeleton、Space.Compact、Spin、Splitter、Transfer 和 Watermark 的 `nativeElement` ref,用于访问各自的根 DOM 元素。[#58627](https://github.com/ant-design/ant-design/pull/58627) [#58628](https://github.com/ant-design/ant-design/pull/58628) [#58629](https://github.com/ant-design/ant-design/pull/58629) [#58630](https://github.com/ant-design/ant-design/pull/58630) [#58631](https://github.com/ant-design/ant-design/pull/58631) [#58632](https://github.com/ant-design/ant-design/pull/58632) [#58633](https://github.com/ant-design/ant-design/pull/58633) [#58634](https://github.com/ant-design/ant-design/pull/58634) [#58635](https://github.com/ant-design/ant-design/pull/58635) [#58636](https://github.com/ant-design/ant-design/pull/58636) [#58637](https://github.com/ant-design/ant-design/pull/58637) [#58638](https://github.com/ant-design/ant-design/pull/58638) [#58639](https://github.com/ant-design/ant-design/pull/58639) [#58640](https://github.com/ant-design/ant-design/pull/58640) [#58641](https://github.com/ant-design/ant-design/pull/58641) [#58642](https://github.com/ant-design/ant-design/pull/58642) [#58643](https://github.com/ant-design/ant-design/pull/58643) [#58644](https://github.com/ant-design/ant-design/pull/58644) [#58645](https://github.com/ant-design/ant-design/pull/58645) [#58667](https://github.com/ant-design/ant-design/pull/58667) [@li-jia-nan](https://github.com/li-jia-nan)
- 🤖 补充导出 Alert、Carousel、Cascader、Masonry、Mentions、Radio、Slider、Statistic、Table、Tabs、Tooltip 和 Upload 缺失的公开 Props 与 Ref 类型。[#58700](https://github.com/ant-design/ant-design/pull/58700) [#58798](https://github.com/ant-design/ant-design/pull/58798) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Calendar、ColorPicker、DatePicker、Divider、Dropdown、Input、Masonry、Popover、Popconfirm、QRCode、Space、Spin、Tag、TimePicker、Tooltip、Typography、Badge、Drawer、FloatButton、Image、Message、Modal、Notification、Steps、Timeline、Tour 和 Upload 同时使用 ConfigProvider 与组件级 `style`、`styles` 时的语义样式优先级。[#58550](https://github.com/ant-design/ant-design/pull/58550) [#58564](https://github.com/ant-design/ant-design/pull/58564) [@QDyanbing](https://github.com/QDyanbing)
- Select
- 🐞 修复 Select 占位文本在祖先元素隐藏时仍然可见的问题。[#58572](https://github.com/ant-design/ant-design/pull/58572) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Select 清除图标在暗色模式下显示原生按钮背景的问题。[#58928](https://github.com/ant-design/ant-design/pull/58928) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Drawer 启用 `closable.disabled` 后关闭按钮仍可交互的问题。[#58853](https://github.com/ant-design/ant-design/pull/58853) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Carousel 动态添加子项时自动跳回第一张的问题。[#58845](https://github.com/ant-design/ant-design/pull/58845) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Button 开始 `loading` 动画时的布局跳动问题。[#58690](https://github.com/ant-design/ant-design/pull/58690) [#58712](https://github.com/ant-design/ant-design/pull/58712) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Typography 省略提示提前关闭导致无法与弹层交互的问题,并优化操作按钮附近的悬浮交互。[#58661](https://github.com/ant-design/ant-design/pull/58661) [#58722](https://github.com/ant-design/ant-design/pull/58722) [@zombieJ](https://github.com/zombieJ)
- 💄 优化 Select、Tree 和 Table 虚拟滚动条轨道的交互反馈,并支持点击 Table 滚动条轨道快速跳转。[#58625](https://github.com/ant-design/ant-design/pull/58625) [#58658](https://github.com/ant-design/ant-design/pull/58658) [@QDyanbing](https://github.com/QDyanbing)
## 6.5.4
`2026-08-07`
- 🐞 修复 Alert 的 `closable` 配置对象仅包含 `onClose` 时不显示关闭按钮的问题。[#58885](https://github.com/ant-design/ant-design/pull/58885) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Checkbox.Group 的 `options` 包含空值选项或空值 `value` 时崩溃的问题。[#58879](https://github.com/ant-design/ant-design/pull/58879) [@GuillaumeZ2SS](https://github.com/GuillaumeZ2SS)
- 🐞 修复 App 使用 `component={false}` 时产生不必要的 CSS 变量警告,并在此模式下无法应用根节点属性时给出提示。[#58877](https://github.com/ant-design/ant-design/pull/58877) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Table 全选数据时仍会选中其他分页中禁用行的问题。[#58843](https://github.com/ant-design/ant-design/pull/58843) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Transfer 筛选后取消全选行为异常的问题。[#58844](https://github.com/ant-design/ant-design/pull/58844) [@thlovey](https://github.com/thlovey)
- 🐞 修复 DatePicker `RangePicker` 语义化回调未透传 props 的问题。[#58905](https://github.com/ant-design/ant-design/pull/58905) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 FloatButton.BackTop 滚动动画未遵循 `prefers-reduced-motion` 设置的问题。[#58849](https://github.com/ant-design/ant-design/pull/58849) [@li-jia-nan](https://github.com/li-jia-nan)
- 💄 修复 Breadcrumb、Collapse、Segmented、Tabs 和 Tag 使用第三方图标库的原生 `` 图标时可能出现对齐异常、间距缺失,或在 CSS reset 下换行的问题。[#58862](https://github.com/ant-design/ant-design/pull/58862) [#58868](https://github.com/ant-design/ant-design/pull/58868) [#58869](https://github.com/ant-design/ant-design/pull/58869) [#58870](https://github.com/ant-design/ant-design/pull/58870) [@mohamedkhaled4053](https://github.com/mohamedkhaled4053)
- 💄 修复 AutoComplete 禁用状态下文本未使用禁用文字颜色的问题。[#58838](https://github.com/ant-design/ant-design/pull/58838) [@lazerg](https://github.com/lazerg)
- 🤖 修复 Tour 暴露无法在单个步骤中使用的 `indicatorsRender` 和 `actionsRender` TypeScript 类型定义的问题。[#58859](https://github.com/ant-design/ant-design/pull/58859) [@lazerg](https://github.com/lazerg)
## 6.5.3
`2026-07-31`
- Input
- 🐞 修复 Input.OTP 使用字符串 `mask` 时仍采用 `type="text"` 的问题,并保留显式 `type` 配置。[#58835](https://github.com/ant-design/ant-design/pull/58835) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Input.OTP 的 `mask` 为 `true` 时仍显示原始值的问题。[#58805](https://github.com/ant-design/ant-design/pull/58805) [@cyphercodes](https://github.com/cyphercodes)
- 💄 修复 Input.TextArea 调整大小手柄在触摸设备上显示为小圆点的问题。[#58812](https://github.com/ant-design/ant-design/pull/58812) [@pupuking723](https://github.com/pupuking723)
- Typography
- ⚡️ 优化 Typography 省略提示在大列表中的渲染性能。[#58806](https://github.com/ant-design/ant-design/pull/58806) [@lkxdsb](https://github.com/lkxdsb)
- 🐞 修复 Typography 可编辑文本框字号与被编辑内容不一致的问题。[#58551](https://github.com/ant-design/ant-design/pull/58551) [@gaurav0107](https://github.com/gaurav0107)
- 🐞 修复 DatePicker.RangePicker 使用 `showTime` 和 `allowEmpty` 时失焦会提交未确认部分值的问题。[#58803](https://github.com/ant-design/ant-design/pull/58803) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Form.Item `useStatus` 在校验状态未变化时返回旧错误和警告内容的问题。[#58815](https://github.com/ant-design/ant-design/pull/58815) [@afc163](https://github.com/afc163)
- 🐞 修复 Slider 的 `onFocus` 和 `onBlur` 回调被重复触发的问题。[#58711](https://github.com/ant-design/ant-design/pull/58711) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Spin 独立加载指示器嵌套使用时定位错乱的问题。[#58801](https://github.com/ant-design/ant-design/pull/58801) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Table 受控筛选面板保持打开时选中项未同步更新的问题。[#58816](https://github.com/ant-design/ant-design/pull/58816) [@afc163](https://github.com/afc163)
- 🐞 修复 Upload 默认下载打开的新页面可访问来源页面的问题。[#58817](https://github.com/ant-design/ant-design/pull/58817) [@afc163](https://github.com/afc163)
- 💄 修复启用 `theme.zeroRuntime` 或 CSS layer 时 Icon 基础样式不完整的问题。[#58763](https://github.com/ant-design/ant-design/pull/58763) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Select 自定义主题色下后缀图标或选中内容与清除图标重叠的问题。[#58581](https://github.com/ant-design/ant-design/pull/58581) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Tabs 中第三方 `` 图标与标签文字垂直方向未对齐的问题。[#58847](https://github.com/ant-design/ant-design/pull/58847) [@mohamedkhaled4053](https://github.com/mohamedkhaled4053)
## 6.5.2
`2026-07-24`
- 💄 修复 Button、Collapse、ColorPicker、Layout、Select、Space.Addon、Tree 和 Typography 边框未响应全局 `lineWidth` 与 `lineType` Design Token 的问题。[#58740](https://github.com/ant-design/ant-design/pull/58740) [#58741](https://github.com/ant-design/ant-design/pull/58741) [#58742](https://github.com/ant-design/ant-design/pull/58742) [#58743](https://github.com/ant-design/ant-design/pull/58743) [#58745](https://github.com/ant-design/ant-design/pull/58745) [#58755](https://github.com/ant-design/ant-design/pull/58755) [@li-jia-nan](https://github.com/li-jia-nan) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 BorderBeam、Checkbox 和 Switch 的 reduced-motion 样式导致 Lightning CSS 压缩失败的问题。[#58707](https://github.com/ant-design/ant-design/pull/58707) [@QDyanbing](https://github.com/QDyanbing)
- Tag
- 💄 修复 Tag 中第三方图标库的原生 `` 图标缺少间距且垂直对齐异常的问题。[#58723](https://github.com/ant-design/ant-design/pull/58723) [@mohamedkhaled4053](https://github.com/mohamedkhaled4053)
- 🐞 修复 Tag 同时配置 `href` 和 `closable` 时,点击关闭图标仍会触发链接跳转的问题。[#58720](https://github.com/ant-design/ant-design/pull/58720) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Input.OTP 根节点丢失 `onPointerDown`、`onAnimationEnd`、`onTransitionEnd` 和 `onScrollEnd` 等 DOM 事件回调的问题。[#58697](https://github.com/ant-design/ant-design/pull/58697) [react-component/util#794](https://github.com/react-component/util/pull/794) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 修复 Form 在 React 19 中使用 UMD 开发构建时触发 Hook 调用顺序警告的问题。[#58417](https://github.com/ant-design/ant-design/pull/58417) [@biubiukam](https://github.com/biubiukam)
- 💄 修复 Table 带边框的嵌套表格被 Tabs 或自定义内容包裹时缺少上边框的问题。[#58746](https://github.com/ant-design/ant-design/pull/58746) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Input.Search 自定义 `enterButton` 未响应组件 `disabled` 和 `loading` 状态的问题。[#58726](https://github.com/ant-design/ant-design/pull/58726) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Transfer 通过 `actions` 传入的自定义操作按钮未保留自身 `disabled` 状态的问题。[#58718](https://github.com/ant-design/ant-design/pull/58718) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Tree `rootStyle` 不生效的问题,并废弃该属性,推荐使用 `styles.root`。[#58709](https://github.com/ant-design/ant-design/pull/58709) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Grid Col 在普通和响应式配置中忽略 `flex` 属性数值 `0` 的问题。[#58719](https://github.com/ant-design/ant-design/pull/58719) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 InputNumber 在 Form 开启反馈状态时不显示 `suffix` 的问题。[#58703](https://github.com/ant-design/ant-design/pull/58703) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ 修复 Splitter 在容器尺寸测量前百分比 `aria-valuemin` 和 `aria-valuemax` 取值异常,以及相邻面板尺寸为 0 时 `lazy` 拖拽预览越界的问题。[#58702](https://github.com/ant-design/ant-design/pull/58702) [@QDyanbing](https://github.com/QDyanbing)
- 📖 修复 ant.design 首页主题预览在重新渲染时重置已选主题的问题。[#58687](https://github.com/ant-design/ant-design/pull/58687) [@meet-student](https://github.com/meet-student)
- 📝 修正 Anchor 中文文档中 `offsetTop` 的默认值为 `0`。[#58710](https://github.com/ant-design/ant-design/pull/58710) [@dogledogle](https://github.com/dogledogle)
## 6.5.1
`2026-07-13`
- 💄 修复 AutoComplete 自定义输入组件在 `filled` 形态下背景色重复叠加的问题。[#58669](https://github.com/ant-design/ant-design/pull/58669) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Avatar、List、Pagination、Steps 和 Table 动态启用响应式配置后无法响应断点变化的问题。[#58654](https://github.com/ant-design/ant-design/pull/58654) [@li-jia-nan](https://github.com/li-jia-nan)
- ⌨️ 修复 Button、Checkbox、Switch、Splitter 和 BorderBeam 的伪元素过渡与动画,使其遵循 `prefers-reduced-motion` 设置。[#58685](https://github.com/ant-design/ant-design/pull/58685) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Button 图标在 Card `extra` 中垂直对齐的问题。[#58584](https://github.com/ant-design/ant-design/pull/58584) [@zombieJ](https://github.com/zombieJ)
- ConfigProvider
- 🐞 修复 ConfigProvider 配合 StyleProvider `layer` 使用时部分组件样式可能丢失的问题。[#58559](https://github.com/ant-design/ant-design/pull/58559) [@fireairforce](https://github.com/fireairforce)
- 🐞 修复 ConfigProvider 动态修改 `prefixCls` 后 CSS 变量前缀未更新的问题。[#58652](https://github.com/ant-design/ant-design/pull/58652) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Descriptions 嵌套在 Popover 中时内容列宽度塌缩的问题。[#58583](https://github.com/ant-design/ant-design/pull/58583) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Dropdown 子组件不支持 `ref` 时弹层定位与交互异常的问题。[#58662](https://github.com/ant-design/ant-design/pull/58662) [@afc163](https://github.com/afc163)
- Form
- 🐞 修复 Form.Item 设置 `help={false}` 时仍展示校验提示的问题。[#58558](https://github.com/ant-design/ant-design/pull/58558) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Form.Item 动态配置变化后反馈图标类名与嵌套 `noStyle` 反馈状态未更新的问题。[#58653](https://github.com/ant-design/ant-design/pull/58653) [@li-jia-nan](https://github.com/li-jia-nan)
- 💄 修复 Icon `TwitchFilled` 相比其他图标偏小且带有意外投影的问题。[#58542](https://github.com/ant-design/ant-design/pull/58542) [ant-design-icons#747](https://github.com/ant-design/ant-design-icons/pull/747) [@mohamedkhaled4053](https://github.com/mohamedkhaled4053)
- ⌨️ 修复 Input.Search 搜索按钮的聚焦轮廓在相邻 Input 进入 hover 态时被覆盖的问题。[#58615](https://github.com/ant-design/ant-design/pull/58615) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Modal 方法将 `classNames.body`、`styles.body` 和 `bodyStyle` 错误应用到确认弹窗标题的问题。[#58412](https://github.com/ant-design/ant-design/pull/58412) [@biubiukam](https://github.com/biubiukam)
- 🐞 修复 Pagination 每页条数选择器在 Form.Item 中被撑满宽度的问题。[#58579](https://github.com/ant-design/ant-design/pull/58579) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Switch 的 `checkedChildren` 和 `unCheckedChildren` 中图标未垂直居中的问题。[#58672](https://github.com/ant-design/ant-design/pull/58672) [@mohamedkhaled4053](https://github.com/mohamedkhaled4053)
- Table
- 🐞 修复 Table 横向滚动时旧的延迟同步任务可能导致滚动位置回跳的问题。[#58613](https://github.com/ant-design/ant-design/pull/58613) [#58622](https://github.com/ant-design/ant-design/pull/58622) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Table 重新打开筛选下拉框时选中项未重置为当前筛选值的问题。[#58657](https://github.com/ant-design/ant-design/pull/58657) [@li-jia-nan](https://github.com/li-jia-nan)
- Typography
- ⌨️ 修复 Typography 的 `ellipsis.rows` 或可编辑文本变化后省略模式与 `aria-label` 未更新的问题。[#58650](https://github.com/ant-design/ant-design/pull/58650) [@li-jia-nan](https://github.com/li-jia-nan)
- 🇯🇵 修复 Typography 日语 `expand` 和 `collapse` 文案语义错误。[#58563](https://github.com/ant-design/ant-design/pull/58563) [@greymoth-jp](https://github.com/greymoth-jp)
- 🌐 补全 ConfigProvider、Table、Transfer、Typography、Form、QRCode、ColorPicker 和 Icon 在 68 个语言包中缺失的本地化文案。[#58575](https://github.com/ant-design/ant-design/pull/58575) [@li-jia-nan](https://github.com/li-jia-nan)
## 6.5.0
`2026-06-27`
- 🔥 新增 antd `DESIGN.md` 设计语言文件并发布到 [ant.design/design.md](https://ant.design/design.md),帮助 AI 设计工具理解 Ant Design 的视觉语言、组件范式和主题 token。[#58011](https://github.com/ant-design/ant-design/pull/58011) [#58356](https://github.com/ant-design/ant-design/pull/58356) [#58489](https://github.com/ant-design/ant-design/pull/58489) [@afc163](https://github.com/afc163)
- 📦 优化 antd 完整包体积:相比 6.4.5,size-limit 中 `antd.min.js` 从 `437.05 KB` 降至 `432.44 KB`,`antd-with-locales.min.js` 从 `514.19 KB` 降至 `506.84 KB`。主要来自 `@rc-component/picker` 精简 DatePicker 和 TimePicker 运行时代码,以及 Icon/Upload 减少额外 TwoTone runtime 引入。[#58403](https://github.com/ant-design/ant-design/pull/58403) [#58497](https://github.com/ant-design/ant-design/pull/58497) [@QDyanbing](https://github.com/QDyanbing) [@afc163](https://github.com/afc163)
- Icon
- 🔥 新增 Icon 内置图标:Anthropic、Claude、Gemini、Mistral、DeepSeek、Qwen、Perplexity、HuggingFace、Ollama、Replicate、ElevenLabs、Telegram、Mastodon、Threads 和 Snapchat。[#58524](https://github.com/ant-design/ant-design/pull/58524) [@afc163](https://github.com/afc163)
- 📦 优化 Icon 和 Upload 默认图标引入:升级 `@ant-design/icons` 到 `6.3.1`,并将 Upload 图片列表默认占位图标改为 Outlined 图标,减少完整包额外 TwoTone runtime 引入。[#58497](https://github.com/ant-design/ant-design/pull/58497) [@afc163](https://github.com/afc163)
- 🐞 修复 Icon 在开启 `theme.zeroRuntime` 后样式不生效的问题。[#58517](https://github.com/ant-design/ant-design/pull/58517) [@afc163](https://github.com/afc163)
- Input
- 🆕 新增 Input.Password `visibilityToggle.tabIndex` 配置,支持自定义密码显隐切换按钮的 Tab 顺序。[#58458](https://github.com/ant-design/ant-design/pull/58458) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Input.Search 未应用 ConfigProvider 根节点 `style` 配置的问题。[#58467](https://github.com/ant-design/ant-design/pull/58467) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Input.Search 丢失 `enterButton.className` 的问题。[#58506](https://github.com/ant-design/ant-design/pull/58506) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Input.Search 按钮高度未与 Input token 高度对齐的问题。[#58525](https://github.com/ant-design/ant-design/pull/58525) [@afc163](https://github.com/afc163)
- 💄 为 borderless Input 组件补充聚焦轮廓样式。[#58250](https://github.com/ant-design/ant-design/pull/58250) [@QDyanbing](https://github.com/QDyanbing)
- Select
- 🆕 新增 Select 函数式 `tokenSeparators` 支持。[#57966](https://github.com/ant-design/ant-design/pull/57966) [@ZQDesigned](https://github.com/ZQDesigned)
- 🐞 修复 Select 及相关弹层组件传入数字类型弹层宽度时渲染不正确的问题。[#58511](https://github.com/ant-design/ant-design/pull/58511) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Select 会创建禁用标签的问题。[#58518](https://github.com/ant-design/ant-design/pull/58518) [@afc163](https://github.com/afc163)
- 🐞 修复 Select 单选模式在打开时 `labelRender` 内容变暗的问题。[#58288](https://github.com/ant-design/ant-design/pull/58288) [@kfylaktopoulos](https://github.com/kfylaktopoulos)
- Table
- 🐞 修复 Table 列设置 `responsive` 后,在当前断点隐藏时 `defaultSortOrder` 与受控 `sortOrder` 不生效的问题。[#58008](https://github.com/ant-design/ant-design/pull/58008) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 修复 Table bordered 模式下最后一个右固定列出现额外竖线的问题。[#58516](https://github.com/ant-design/ant-design/pull/58516) [@uttam12331](https://github.com/uttam12331)
- ⌨️ 优化 Table 行选择复选框的可访问性,支持从 `getCheckboxProps` 传入 `aria-*` 属性。[#58275](https://github.com/ant-design/ant-design/pull/58275) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 修复 Table bordered 模式下 sticky 表头顶部边框丢失的问题。[#58451](https://github.com/ant-design/ant-design/pull/58451) [@BangDori](https://github.com/BangDori)
- BorderBeam
- 🆕 新增 BorderBeam `duration` 属性,用于控制流光运行一圈的时间。[#58233](https://github.com/ant-design/ant-design/pull/58233) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 BorderBeam `lineWidth` 属性,用于控制流光宽度。[#58324](https://github.com/ant-design/ant-design/pull/58324) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 BorderBeam `size` 属性,用于控制流光大小。[#58303](https://github.com/ant-design/ant-design/pull/58303) [@QDyanbing](https://github.com/QDyanbing)
- Badge
- 🆕 新增 Badge `title` 属性,支持移除原生 tooltip。[#58209](https://github.com/ant-design/ant-design/pull/58209) [@QDyanbing](https://github.com/QDyanbing)
- 💄 优化 Badge 在暗色模式下 processing 状态的展示效果。[#58414](https://github.com/ant-design/ant-design/pull/58414) [@clxstart](https://github.com/clxstart)
- Layout
- 🆕 新增 Layout.Sider 语义化 `classNames` 和 `styles` 支持。[#57938](https://github.com/ant-design/ant-design/pull/57938) [@landeqiming666](https://github.com/landeqiming666)
- 🐞 修复 Layout.Header、Layout.Footer 和 Layout.Content 独立使用且开启 `theme.cssVar` 时默认背景色丢失的问题。[#58046](https://github.com/ant-design/ant-design/pull/58046) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- Pagination
- 🐞 修复 Pagination 在部分场景下文字换行和溢出的问题。[#58151](https://github.com/ant-design/ant-design/pull/58151) [@selicens](https://github.com/selicens)
- 🐞 修复 Pagination 快速跳转布局不稳定的问题。[#58282](https://github.com/ant-design/ant-design/pull/58282) [@QDyanbing](https://github.com/QDyanbing)
- Upload
- 🐞 修复 Upload 上传失败文件不展示文件图标的问题。[#58484](https://github.com/ant-design/ant-design/pull/58484) [@biubiukam](https://github.com/biubiukam)
- ⌨️ 改进 Upload 在无 URL 文件预览场景下文件名的无障碍体验。[#58092](https://github.com/ant-design/ant-design/pull/58092) [@ug-one](https://github.com/ug-one)
- Alert
- 🐞 修复 Alert 带有描述内容时图标垂直对齐异常的问题。[#57915](https://github.com/ant-design/ant-design/pull/57915) [@MMMIXER](https://github.com/MMMIXER)
- 🐞 修复 Alert 仅包含标题时图标和关闭按钮未与标题首行对齐的问题。[#57878](https://github.com/ant-design/ant-design/pull/57878) [@QDyanbing](https://github.com/QDyanbing)
- 📖 优化 ant.design 网站的 AI 智能体支持,提升 [isitagentready.com/ant.design](https://isitagentready.com/ant.design) 检测结果。[#58510](https://github.com/ant-design/ant-design/pull/58510) [#58490](https://github.com/ant-design/ant-design/pull/58490) [#57725](https://github.com/ant-design/ant-design/pull/57725) [@afc163](https://github.com/afc163) [@ug-one](https://github.com/ug-one)
- 📖 更新 Ant Design CLI 文档,补充 `antd setup`、Node.js `>=20.0.0` 要求、MCP 版本自动检测和环境变量说明,并同步 For Agents 与 MCP Server 中英文文档。[#58460](https://github.com/ant-design/ant-design/pull/58460) [@afc163](https://github.com/afc163)
- 🐞 修复 antd 各组件根节点语义化 `style` 优先级,确保组件 `style` 覆盖全局 `styles.root` 与 `style` 配置。[#58474](https://github.com/ant-design/ant-design/pull/58474) [@QDyanbing](https://github.com/QDyanbing)
- 💄 优化 Component Token 紧凑主题下小尺寸控件高度,避免文字行框过于拥挤。[#58411](https://github.com/ant-design/ant-design/pull/58411) [@nightt5879](https://github.com/nightt5879)
- 🐞 修复 Anchor 在特殊构造的 hash 值下解析性能异常的问题。[#58472](https://github.com/ant-design/ant-design/pull/58472) [@afc163](https://github.com/afc163)
- 🆕 新增 Collapse `headerPaddingSM`、`headerPaddingLG`、`contentPaddingSM` 和 `contentPaddingLG` token,支持分别配置小号和大号尺寸的头部与内容区域内边距。[#58436](https://github.com/ant-design/ant-design/pull/58436) [@biubiukam](https://github.com/biubiukam)
- 🆕 新增 ConfigProvider form `labelWrap` 全局配置支持。[#58035](https://github.com/ant-design/ant-design/pull/58035) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Descriptions 在 `bordered` 模式下 `labelStyle`、`contentStyle` 以及语义化 `styles.label`、`styles.content` 未应用到对应单元格的问题。[#58241](https://github.com/ant-design/ant-design/pull/58241) [@gaurav0107](https://github.com/gaurav0107)
- 🔥 新增 DatePicker 和 TimePicker `onClear` 回调支持。[#58403](https://github.com/ant-design/ant-design/pull/58403) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Dropdown `left` 和 `right` 弹出位置支持。[#58437](https://github.com/ant-design/ant-design/pull/58437) [@linyana](https://github.com/linyana)
- 🐞 修复 FloatButton.Group 禁用状态下仍会打开 hover 菜单的问题。[#58513](https://github.com/ant-design/ant-design/pull/58513) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Form 垂直布局未应用 `labelHeight` token 的问题。[#58433](https://github.com/ant-design/ant-design/pull/58433) [@BangDori](https://github.com/BangDori)
- 🔥 新增 Menu `onSelect`、`onClick` 和 `onDeselect` 回调参数中的 `itemData` 信息。[#58197](https://github.com/ant-design/ant-design/pull/58197) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🔥 新增 Modal `scrollLock` 属性,用于控制弹窗打开时是否锁定 body 滚动。[#58256](https://github.com/ant-design/ant-design/pull/58256) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Popconfirm 异步确认时按钮不对齐的问题,并恢复 Button 图标按钮与 Modal footer 的默认布局表现。[#58429](https://github.com/ant-design/ant-design/pull/58429) [@ffgenius](https://github.com/ffgenius)
- 🐞 修复 Result 在 `extra` 为数字 `0` 时不渲染的问题。[#58504](https://github.com/ant-design/ant-design/pull/58504) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Slider Range 模式下 `disabled` 数组支持,可单独禁用特定 handle。[#57982](https://github.com/ant-design/ant-design/pull/57982) [#58528](https://github.com/ant-design/ant-design/pull/58528) [@EmilyyyLiu](https://github.com/EmilyyyLiu) [@afc163](https://github.com/afc163)
- Steps
- 🆕 新增 Steps `maxCount` 折叠模式,用于展示密集步骤项。[#57987](https://github.com/ant-design/ant-design/pull/57987) [@ZQDesigned](https://github.com/ZQDesigned)
- 💄 修复 Steps 横向连接线在 Chrome 中显示模糊的问题。[#58149](https://github.com/ant-design/ant-design/pull/58149) [@olagokemills](https://github.com/olagokemills)
- 🔥 新增 Tabs `body` 和 `content` 语义化 DOM 支持。[#58521](https://github.com/ant-design/ant-design/pull/58521) [@zombieJ](https://github.com/zombieJ)
- 🆕 新增 Watermark `content` 逐行字体样式支持。[#57886](https://github.com/ant-design/ant-design/pull/57886) [@QDyanbing](https://github.com/QDyanbing)
## 6.4.5
`2026-06-22`
- 🐞 修复 Dropdown 纵向菜单在触发器位于屏幕中部时溢出视口、顶部菜单项无法点击的问题。[#58214](https://github.com/ant-design/ant-design/pull/58214) [@18062706139fcz](https://github.com/18062706139fcz)
- 🐞 修复 Alert 在开启 hashed 样式时 `actions` 间距不生效的问题。[#58314](https://github.com/ant-design/ant-design/pull/58314) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ 修复 Table 在 `scroll` 生成多个 table 时,固定表头 table 未应用 `aria-*` 属性的问题。[#58339](https://github.com/ant-design/ant-design/pull/58339) [@biubiukam](https://github.com/biubiukam)
- 💄 修复 Pagination 快速跳转输入框未跟随 ConfigProvider `variant` 样式的问题。[#58371](https://github.com/ant-design/ant-design/pull/58371) [@biubiukam](https://github.com/biubiukam)
- 🌐 国际化
- 🇳🇴 补充 nb_NO(挪威语)缺失的 locale 本地化键值。[#58439](https://github.com/ant-design/ant-design/pull/58439) [@arvindfroi](https://github.com/arvindfroi)
## 6.4.4
`2026-06-12`
- 🛠 修复多个组件在 Vite、Yarn PnP、Node 25 等严格 ESM 环境下因引用 rc 组件包深路径导致构建失败的问题。[#58115](https://github.com/ant-design/ant-design/issues/58115) [@li-jia-nan](https://github.com/li-jia-nan) [@QDyanbing](https://github.com/QDyanbing)
- 🛠 修复多个组件在 ReactNode 内容为空字符串时渲染空包装 DOM 节点的问题。[#58160](https://github.com/ant-design/ant-design/pull/58160) [@QDyanbing](https://github.com/QDyanbing)
- Descriptions
- 🐞 修复 Descriptions 嵌套 Table 时宽度可能被异常撑大的问题。[#58203](https://github.com/ant-design/ant-design/pull/58203) [@18062706139fcz](https://github.com/18062706139fcz)
- 🐞 修复 Descriptions 传入响应式 `column` 属性值时行为可能不符合预期的问题。[#58058](https://github.com/ant-design/ant-design/pull/58058) [@kfylaktopoulos](https://github.com/kfylaktopoulos)
- Radio
- 🐞 修复 Radio.Group button 形态在垂直布局下圆角和相邻边框展示异常的问题。[#58317](https://github.com/ant-design/ant-design/pull/58317) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Radio 非受控模式下点击后选中状态不更新的问题。[#57917](https://github.com/ant-design/ant-design/pull/57917) [@QDyanbing](https://github.com/QDyanbing)
- Table
- 🐞 修复 Table 开启 `virtual` 模式时部分语义化 DOM 结构不正确的问题。[#58134](https://github.com/ant-design/ant-design/pull/58134) [@meet-student](https://github.com/meet-student)
- ⌨️ 优化 Table 筛选下拉框外层容器的无障碍语义为展示用途。[#58164](https://github.com/ant-design/ant-design/pull/58164) [@ug-hero](https://github.com/ug-hero)
- Tour
- ⌨️ 修复 Tour 主色模式下 hover 上一步按钮时文字颜色的可读性问题。[#58311](https://github.com/ant-design/ant-design/pull/58311) [@QDyanbing](https://github.com/QDyanbing)
- 🇰🇭 补全 Tour 的高棉语 km_KH 本地化文案。[#58140](https://github.com/ant-design/ant-design/pull/58140) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- Transfer
- ⌨️ 修复 Transfer 未透传根 HTML 属性影响可访问性的问题。[#58166](https://github.com/ant-design/ant-design/pull/58166) [@ZQDesigned](https://github.com/ZQDesigned)
- ⚡️ 优化 Transfer 收集可用项 key 时的遍历性能。[#58168](https://github.com/ant-design/ant-design/pull/58168) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Menu 折叠时图标动画可能发生跳动的问题。[#58271](https://github.com/ant-design/ant-design/pull/58271) [@murisans](https://github.com/murisans)
- 🐞 修复 Modal 在 `confirmLoading` 为 `true` 时 footer 按钮垂直方向错位的问题。[#58120](https://github.com/ant-design/ant-design/pull/58120) [@xxiaoxiong](https://github.com/xxiaoxiong)
- 🐞 修复 Notification 在未传入 title 时关闭按钮与描述内容重叠的问题。[#58096](https://github.com/ant-design/ant-design/pull/58096) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Popover 与 Popconfirm 在 `title` 或 `content` 为数字 `0` 时不渲染的问题。[#58296](https://github.com/ant-design/ant-design/pull/58296) [@afc163](https://github.com/afc163)
- 🐞 修复 Slider 滑块在 Safari 中拖动时周围文本可能被意外选中的问题。[#58024](https://github.com/ant-design/ant-design/pull/58024) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 修复 Tabs 更多菜单在向上弹出时动画方向错误的问题。[#58202](https://github.com/ant-design/ant-design/pull/58202) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Tree.DirectoryTree 设置 `defaultExpandParent` 不生效的问题。[#58068](https://github.com/ant-design/ant-design/pull/58068) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Upload 未配置 progress 时进度条异常变粗的问题。[#58126](https://github.com/ant-design/ant-design/pull/58126) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Icon 在存在多个 `iconPrefixCls` 时旋转动画停止的问题。[#58253](https://github.com/ant-design/ant-design/pull/58253) [@18062706139fcz](https://github.com/18062706139fcz)
- 💄 修复 AutoComplete 禁用自定义输入组件时背景色比其他禁用控件更深的问题。[#58114](https://github.com/ant-design/ant-design/pull/58114) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Checkbox 在移动端设备上点击时残留 hover 样式。[#58085](https://github.com/ant-design/ant-design/pull/58085) [@unknowntocka](https://github.com/unknowntocka)
- 💄 修复 Empty 组件未使用 design tokens 来支持暗色模式下的 SVG 颜色。[#58152](https://github.com/ant-design/ant-design/pull/58152) [@wanpan11](https://github.com/wanpan11)
- 💄 修复 Result 和 Popconfirm 图标颜色可能被全局图标 reset 样式覆盖的问题。[#58157](https://github.com/ant-design/ant-design/pull/58157) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Select 选中项激活态背景色不是主题色的问题。[#58069](https://github.com/ant-design/ant-design/pull/58069) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Tooltip 和 Popover 箭头阴影比容器深的问题。[#57988](https://github.com/ant-design/ant-design/pull/57988) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 加深 `boxShadowTertiary` 阴影,提升浅色背景下的可见度,影响 Card、Tour 和 Segmented 组件。[#58205](https://github.com/ant-design/ant-design/pull/58205) [@afc163](https://github.com/afc163)
- ⌨️ 优化 ColorPicker 清除按钮的语义化属性以提升可访问性。[#58040](https://github.com/ant-design/ant-design/pull/58040) [@ug-hero](https://github.com/ug-hero)
- ⌨️ 提升 DatePicker 及 TimePicker 清除按钮的可访问性。[#58132](https://github.com/ant-design/ant-design/pull/58132) [@Pareder](https://github.com/Pareder)
- ⌨️ 优化 Splitter 分隔条的语义化属性以提升可访问性。[#58060](https://github.com/ant-design/ant-design/pull/58060) [@ug-hero](https://github.com/ug-hero)
- ⌨️ 优化 Tag.CheckableTag 的语义化属性以提升可访问性。[#58067](https://github.com/ant-design/ant-design/pull/58067) [@ug-hero](https://github.com/ug-hero)
- 🛠 修复 Dropdown 触发节点带有 ref 时在 React 19 下出现 element.ref 废弃警告的问题。[#58056](https://github.com/ant-design/ant-design/pull/58056) [@QDyanbing](https://github.com/QDyanbing)
- 🛠 修复多个组件在 ReactNode 内容为 false 时渲染空包装 DOM 节点的问题。[#58088](https://github.com/ant-design/ant-design/pull/58088) [@QDyanbing](https://github.com/QDyanbing)
- 🌐 国际化
- 🇬🇧 优化 QRCode 及 ColorPicker 英国英语 en_GB 以对齐美国英语 en_US。[#58224](https://github.com/ant-design/ant-design/pull/58224) [@JordanWeatherby](https://github.com/JordanWeatherby)
- 🇧🇷 补充 QRCode 与 ColorPicker 组件缺失的巴西葡萄牙语 pt_BR 国际化文案。[#58188](https://github.com/ant-design/ant-design/pull/58188) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- TypeScript
- 🤖 修复 AutoComplete `showSearch` 类型泄露不支持的 Select 属性的问题。[#58104](https://github.com/ant-design/ant-design/pull/58104) [@sri443](https://github.com/sri443)
- 🤖 完善 Descriptions 类型定义以支持传递原生 HTML 属性。[#58190](https://github.com/ant-design/ant-design/pull/58190) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
## 6.4.3
`2026-05-18`
- 🐞 修复 DatePicker RangePicker 在语言包仅定义单数形式 `*Placeholder` 时占位符为空的问题。[#58020](https://github.com/ant-design/ant-design/pull/58020) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 修复 Result 未传入 `title` 属性时仍会渲染空的标题元素的问题。[#58028](https://github.com/ant-design/ant-design/pull/58028) [@yogeshwaran-c](https://github.com/yogeshwaran-c)
- 🐞 修复 Select 搜索输入框在 Safari 下字号和行高渲染异常的问题。[#57990](https://github.com/ant-design/ant-design/pull/57990) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Form、Input、Button 等组件在严格 ESM 构建链路下因 `@rc-component/util` 运行时深层导入导致的构建报错。[#57993](https://github.com/ant-design/ant-design/pull/57993) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Transfer 在 `filterOption` 或 `direction` 变化时 `filteredItems` 不更新的问题。[#58004](https://github.com/ant-design/ant-design/pull/58004) [@afc163](https://github.com/afc163)
- ⚡️ 优化 Table 和 Mentions 性能,减少冗余的数组迭代操作。[#58006](https://github.com/ant-design/ant-design/pull/58006) [@ug-hero](https://github.com/ug-hero)
- Table
- 🛠 Table 过滤类型将 `FilterRestProps` 更正为 `FilterResetProps`,并保留 deprecated 别名以兼容存量引用。[#57985](https://github.com/ant-design/ant-design/pull/57985) [@ZQDesigned](https://github.com/ZQDesigned)
- ⚡️ 优化 Table 行选择性能,使用 Set 查找替代 O(n*m) 的 `.includes()` 判断。[#58004](https://github.com/ant-design/ant-design/pull/58004) [@afc163](https://github.com/afc163)
## 6.4.2
`2026-05-14`
- 🐞 修复 message 和 notification 在严格 ESM 构建链路下因 rc notification 运行时深层导入导致的构建报错。[#57976](https://github.com/ant-design/ant-design/pull/57976) [@QDyanbing](https://github.com/QDyanbing)
## 6.4.1
`2026-05-14`
- 🐞 回滚 [#57930](https://github.com/ant-design/ant-design/pull/57930) 中新增的 `exports` 字段,修复 antd 在 `moduleResolution: "bundler"` 下 TypeScript 类型解析失败的问题。[#57968](https://github.com/ant-design/ant-design/pull/57968) [@afc163](https://github.com/afc163)
- 🐞 修复 BorderBeam 光束动画在圆角转弯处断开的问题。[#57969](https://github.com/ant-design/ant-design/pull/57969) [@QDyanbing](https://github.com/QDyanbing)
## 6.4.0
`2026-05-14`
- 🔥 新增 BorderBeam 边框流光组件,在容器边框上呈现流动的高光动画效果。[#57720](https://github.com/ant-design/ant-design/pull/57720) [@QDyanbing](https://github.com/QDyanbing)
- ConfigProvider
- 🆕 新增 Select `allowClear` 全局配置支持。[#56476](https://github.com/ant-design/ant-design/pull/56476) [@ug-hero](https://github.com/ug-hero)
- 🆕 新增 Select `showSearch`、`allowClear`、`clearIcon`、`loadingIcon`、`menuItemSelectedIcon`、`removeIcon`、`suffixIcon` 全局配置支持。[#56930](https://github.com/ant-design/ant-design/pull/56930) [@Pareder](https://github.com/Pareder)
- 🆕 新增 DatePicker 和 TimePicker `allowClear` 和 `clearIcon` 全局配置支持。[#57002](https://github.com/ant-design/ant-design/pull/57002) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 RangePicker `allowClear`、`clearIcon`、`suffixIcon` 全局配置支持。[#57075](https://github.com/ant-design/ant-design/pull/57075) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Modal `infoIcon`、`successIcon`、`warningIcon`、`errorIcon` 全局配置支持。[#57168](https://github.com/ant-design/ant-design/pull/57168) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Upload `progress` 全局配置支持。[#57283](https://github.com/ant-design/ant-design/pull/57283) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Upload `accept` 全局配置支持。[#57286](https://github.com/ant-design/ant-design/pull/57286) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Modal 和 Drawer `focusable` 全局配置,控制组件是否可获得焦点。[#57314](https://github.com/ant-design/ant-design/pull/57314) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Mentions `allowClear` 全局配置支持。[#57330](https://github.com/ant-design/ant-design/pull/57330) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 ConfigProvider 的 css var 前缀未跟随 `prefixCls` 的问题。[#57803](https://github.com/ant-design/ant-design/pull/57803) [@QDyanbing](https://github.com/QDyanbing)
- Input
- 🆕 新增 Input `allowClear.disabled` 属性,支持禁用清除按钮但保持可见。[#57240](https://github.com/ant-design/ant-design/pull/57240) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Input.TextArea `allowClear.disabled` 属性,支持禁用清除按钮但保持可见。[#57328](https://github.com/ant-design/ant-design/pull/57328) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Input `clear` 语义化片段,支持自定义清除按钮的 `classNames` 和 `styles`。[#57391](https://github.com/ant-design/ant-design/pull/57391) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Input.Search `searchIcon` 属性,支持自定义搜索图标。[#57256](https://github.com/ant-design/ant-design/pull/57256) [@guoyunhe](https://github.com/guoyunhe)
- ⌨️ 优化 Input.Password 可访问性,支持 ConfigProvider 配置。[#57271](https://github.com/ant-design/ant-design/pull/57271) [@Pareder](https://github.com/Pareder)
- Image
- 🆕 新增 Image `placeholder.progress` 属性,支持显示加载进度指示器。[#57173](https://github.com/ant-design/ant-design/pull/57173) [@afc163](https://github.com/afc163)
- 🆕 新增 Image 预览蒙层 `closable` 支持。[#57611](https://github.com/ant-design/ant-design/pull/57611) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Image `closeIcon` 语义化节点,支持 `classNames` 和 `styles` 配置。[#57263](https://github.com/ant-design/ant-design/pull/57263) [@coding-ice](https://github.com/coding-ice)
- ⌨️ 新增 Image 预览的 focus-visible 样式和 focusTrap 支持。[#57610](https://github.com/ant-design/ant-design/pull/57610) [@aojunhao123](https://github.com/aojunhao123)
- Splitter
- 🆕 新增 Splitter `destroyOnHidden` 属性,用于面板内容挂载管理。[#56772](https://github.com/ant-design/ant-design/pull/56772) [@AhmeddEsmat](https://github.com/AhmeddEsmat)
- 🆕 新增 Splitter 可折叠面板的平滑过渡动画。[#56814](https://github.com/ant-design/ant-design/pull/56814) [@spider-yamet](https://github.com/spider-yamet)
- 🗑 废弃 Splitter `collapsibleIcon`,新增 `collapsible.icon` 替代。[#57044](https://github.com/ant-design/ant-design/pull/57044) [@wanpan11](https://github.com/wanpan11)
- 🐞 修复 Splitter.Panel 存在非预期的 1px 水平内边距。[#57838](https://github.com/ant-design/ant-design/pull/57838) [@wanpan11](https://github.com/wanpan11)
- Select
- 🐞 修复 Select 激活项样式优先级未高于选中项的问题,避免多选模式下键盘操作时看不清当前选项。[#56924](https://github.com/ant-design/ant-design/pull/56924) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Select `showArrowPaddingInlineEnd` token 未作用到内容区尾部间距的问题。[#57769](https://github.com/ant-design/ant-design/pull/57769) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Select error 状态颜色在 outlined 和 filled 变体下与 Input 不一致的问题。[#57807](https://github.com/ant-design/ant-design/pull/57807) [@nickmopen](https://github.com/nickmopen)
- 🐞 修复 Select 选中值字体未跟随 antd 字体 token 的问题。[#57897](https://github.com/ant-design/ant-design/pull/57897) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Select 和 TreeSelect 搜索时 `labelRender` 非文本内容仍可见的问题。[#57954](https://github.com/ant-design/ant-design/pull/57954) [@QDyanbing](https://github.com/QDyanbing)
- Theme
- 🆕 新增 `colorErrorAffix` Design Token,控制输入框后缀的错误状态颜色。[#57604](https://github.com/ant-design/ant-design/pull/57604) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 `colorWarningAffix` Design Token,控制输入框后缀的警告状态颜色。[#57760](https://github.com/ant-design/ant-design/pull/57760) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 Design Token heading 字号令牌不支持字符串值的问题。[#57598](https://github.com/ant-design/ant-design/pull/57598) [@EndlessLucky](https://github.com/EndlessLucky)
- Typography
- 🆕 新增 Typography `actions` 位置配置属性,支持控制操作按钮的摆放位置。[#57440](https://github.com/ant-design/ant-design/pull/57440) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Typography 内表格元素默认样式。[#57633](https://github.com/ant-design/ant-design/pull/57633) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 Typography 更灵活的语义化结构。[#56971](https://github.com/ant-design/ant-design/pull/56971) [@zombieJ](https://github.com/zombieJ)
- Button
- 🆕 新增 Button solid 变体的默认颜色支持。[#57495](https://github.com/ant-design/ant-design/pull/57495) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Button 图标按钮中图标垂直未居中的问题。[#57896](https://github.com/ant-design/ant-design/pull/57896) [@RenzoMXD](https://github.com/RenzoMXD)
- DatePicker
- 🆕 新增 DatePicker 多选模式下 `tagRender` 属性,支持自定义标签渲染。[#57706](https://github.com/ant-design/ant-design/pull/57706) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ 优化 DatePicker 和 TimePicker 的可访问性。[#57400](https://github.com/ant-design/ant-design/pull/57400) [@cyphercodes](https://github.com/cyphercodes)
- Form
- 🆕 新增 ConfigProvider 下 Form `labelAlign` 属性,支持全局控制标签对齐方式。[#56979](https://github.com/ant-design/ant-design/pull/56979) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 Form `help`、`helpItem` 和 `extra` 语义化 DOM 支持,便于自定义样式。[#57607](https://github.com/ant-design/ant-design/pull/57607) [@QDyanbing](https://github.com/QDyanbing)
- Menu
- 🐞 修复 Menu 带图标的 item extra 布局问题。[#57818](https://github.com/ant-design/ant-design/pull/57818) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Menu item extra 省略和 tooltip padding 问题。[#57823](https://github.com/ant-design/ant-design/pull/57823) [@QDyanbing](https://github.com/QDyanbing)
- Notification
- 🆕 新增 Notification 完整语义化结构支持。[#57824](https://github.com/ant-design/ant-design/pull/57824) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Notification 无标题时关闭按钮间距不足的问题。[#57821](https://github.com/ant-design/ant-design/pull/57821) [@QDyanbing](https://github.com/QDyanbing)
- Table
- 🆕 新增 Table `column` 属性,支持通过 ConfigProvider 配置列。[#57545](https://github.com/ant-design/ant-design/pull/57545) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Table `scrollTo` align 参数,升级 rc-table 至 1.10.0。[#57594](https://github.com/ant-design/ant-design/pull/57594) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- Tag
- 🆕 新增 Tag `close` 语义化节点,支持关闭图标 `classNames` 和 `styles` 配置。[#57331](https://github.com/ant-design/ant-design/pull/57331) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Tag CheckableTagGroup 逐项 `className` 和 `style` 支持。[#57840](https://github.com/ant-design/ant-design/pull/57840) [@ZQDesigned](https://github.com/ZQDesigned)
- Tree
- 🆕 新增 Tree 和 TreeSelect 的 `itemSwitcher` 语义化支持。[#57281](https://github.com/ant-design/ant-design/pull/57281) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Tree 右键菜单关闭后焦点回到树导致滚动到顶部的问题。[#57329](https://github.com/ant-design/ant-design/pull/57329) [@aojunhao123](https://github.com/aojunhao123)
- Wave
- 🆕 新增 Wave `triggerType` 配置,控制哪个元素触发水波纹效果。[#57402](https://github.com/ant-design/ant-design/pull/57402) [@wanpan11](https://github.com/wanpan11)
- 🐞 修复 Wave 忽略透明十六进制颜色的问题。[#57859](https://github.com/ant-design/ant-design/pull/57859) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 新增 Alert `variant` 属性,支持 filled 和 outlined 样式变体,并支持 ConfigProvider 配置。[#57764](https://github.com/ant-design/ant-design/pull/57764) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Anchor.Link `targetOffset` 属性,支持为每个链接单独设置滚动偏移。[#57521](https://github.com/ant-design/ant-design/pull/57521) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 App `ref` 支持,可通过 ref 访问实例方法。[#56951](https://github.com/ant-design/ant-design/pull/56951) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 新增 Badge `paddingInline` Design Token。[#57891](https://github.com/ant-design/ant-design/pull/57891) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 新增 Calendar `itemContent` 语义化 DOM 支持。[#57430](https://github.com/ant-design/ant-design/pull/57430) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 新增 Cascader 和 ConfigProvider 的 `searchIcon`、`clearIcon`、`removeIcon`、`suffixIcon` 配置支持。[#56725](https://github.com/ant-design/ant-design/pull/56725) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 Checkbox 在 Form.Item 中冗余设置原生 input 尺寸和宽高的问题。[#57714](https://github.com/ant-design/ant-design/pull/57714) [@lcsy1234](https://github.com/lcsy1234)
- 🐞 修复 Dropdown 缺少 `forwardRef` 导致 React 18 兼容性问题。[#57902](https://github.com/ant-design/ant-design/pull/57902) [@xxiaoxiong](https://github.com/xxiaoxiong)
- 🆕 新增 FloatButton `disabled` 支持。[#57123](https://github.com/ant-design/ant-design/pull/57123) [@zombieJ](https://github.com/zombieJ)
- 🆕 新增 Modal `closeIcon` 语义化节点,支持 `classNames` 和 `styles` 配置。[#57264](https://github.com/ant-design/ant-design/pull/57264) [@divyeshagrawal](https://github.com/divyeshagrawal)
- 🐞 修复 Mentions 弹出层 z-index 问题。[#57873](https://github.com/ant-design/ant-design/pull/57873) [@meet-student](https://github.com/meet-student)
- 🆕 新增 Popconfirm `icon` 语义化节点,支持 `classNames` 和 `styles` 配置。[#57528](https://github.com/ant-design/ant-design/pull/57528) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Space.Addon Design Token 支持。[#56915](https://github.com/ant-design/ant-design/pull/56915) [@zombieJ](https://github.com/zombieJ)
- 🛎 更新 Spin `size` 属性废弃警告并移除冗余检查。[#57812](https://github.com/ant-design/ant-design/pull/57812) [@meet-student](https://github.com/meet-student)
- 🆕 新增 Statistic 数值语义化 `classNames` 和 `styles` 支持。[#57656](https://github.com/ant-design/ant-design/pull/57656) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 新增 Tabs `remove` 语义化节点,支持关闭按钮 `classNames` 和 `styles` 配置。[#57267](https://github.com/ant-design/ant-design/pull/57267) [@coding-ice](https://github.com/coding-ice)
- 🆕 新增 Tour `closeIcon` 语义化节点,支持 `classNames` 和 `styles` 配置。[#57268](https://github.com/ant-design/ant-design/pull/57268) [@coding-ice](https://github.com/coding-ice)
- 🆕 新增 Transfer source 和 target 语义化 DOM 支持。[#57101](https://github.com/ant-design/ant-design/pull/57101) [@QDyanbing](https://github.com/QDyanbing)
- 🆕 新增 Upload 对 avif、tif 和 tiff 图片类型的检测支持。[#57287](https://github.com/ant-design/ant-design/pull/57287) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 Watermark 默认未覆盖 Table 固定列的问题。[#57813](https://github.com/ant-design/ant-design/pull/57813) [@QDyanbing](https://github.com/QDyanbing)
- 🇺🇸 新增 8 种语言的 Form `defaultValidateMessages`。[#57038](https://github.com/ant-design/ant-design/pull/57038) [@mixelburg](https://github.com/mixelburg) [#57045](https://github.com/ant-design/ant-design/pull/57045) [@copilot-swe-agent](https://github.com/apps/copilot-swe-agent)
- 🆕 为 antd `GetProp` 新增 Return 类型支持。[#57001](https://github.com/ant-design/ant-design/pull/57001) [@crazyair](https://github.com/crazyair)
- 📖 新增 Agent Readiness 文件(包含 robots.txt、sitemap、agent-skills、api-catalog 等),提升 ant.design 对 AI 代理的友好度。[#57903](https://github.com/ant-design/ant-design/pull/57903) [@afc163](https://github.com/afc163)
## 6.3.7
`2026-04-27`
- Input
- 🐞 修复 Input.OTP 在 Windows 下选中文本时可能显示真实值的问题。[#57689](https://github.com/ant-design/ant-design/pull/57689) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ 优化 Input 清除按钮的可访问性。[#57432](https://github.com/ant-design/ant-design/pull/57432) [@cyphercodes](https://github.com/cyphercodes)
- 🐞 修复 Card 在未传入内容时仍渲染空 body 容器的问题。[#57735](https://github.com/ant-design/ant-design/pull/57735) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 InputNumber 选中文本时的高亮圆角问题。[#57705](https://github.com/ant-design/ant-design/pull/57705) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Tooltip 的 ConfigProvider 语义化配置比如 `className`、`styles` 等泄漏到 Popover 和 Popconfirm 的问题。[#57731](https://github.com/ant-design/ant-design/pull/57731) [@pikanohup](https://github.com/pikanohup)
- 🐞 修复 Typography.Link 在 disabled 状态下无法触发复制、编辑等操作按钮的问题。[#57762](https://github.com/ant-design/ant-design/pull/57762) [@aviu16](https://github.com/aviu16)
- 🐞 修复 ESM/CJS 默认导出 ConfigProvider 语言包失效的问题。[#57318](https://github.com/ant-design/ant-design/pull/57318) [@ug-hero](https://github.com/ug-hero)
- 💄 修复 Alert 的关闭按钮没有焦点样式的问题。[#57695](https://github.com/ant-design/ant-design/pull/57695) [@KittyGiraudel](https://github.com/KittyGiraudel)
## 6.3.6
`2026-04-17`
- 🐞 修复 InputNumber 禁用步进按钮仍显示悬浮样式的问题。 [#57592](https://github.com/ant-design/ant-design/pull/57592) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Space.Addon 在紧凑布局中展示中文等 CJK 内容时会换行的问题。 [#57622](https://github.com/ant-design/ant-design/pull/57622) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Cascader 菜单项长选项文本的省略样式问题。 [#57540](https://github.com/ant-design/ant-design/pull/57540) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Image 通过键盘打开预览时焦点未被正确锁定的问题,并在关闭预览后恢复焦点到触发元素。 [#57613](https://github.com/ant-design/ant-design/pull/57613) [#57614](https://github.com/ant-design/ant-design/pull/57614) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 修复 Input 禁用状态边框未使用 `colorBorderDisabled` token 的问题。 [#57518](https://github.com/ant-design/ant-design/pull/57518) [@Gdhanush-13](https://github.com/Gdhanush-13)
- 🐞 MISC: 修复部分展开动画崩溃的问题。 [#57636](https://github.com/ant-design/ant-design/pull/57636) [@momesana](https://github.com/momesana)
- 🐞 修复 Notification 在 title 为空时关闭按钮与描述内容重叠的问题。 [#57590](https://github.com/ant-design/ant-design/pull/57590) [@EndlessLucky](https://github.com/EndlessLucky)
- 🐞 修复 Radio 禁用状态下 hover 仍显示主色的问题。 [#57562](https://github.com/ant-design/ant-design/pull/57562) [@yfy3939](https://github.com/yfy3939)
- Table
- ⚡️ 优化 Table 筛选性能,缓存展开后的筛选键,避免重复计算。 [#57546](https://github.com/ant-design/ant-design/pull/57546) [@Jiyur](https://github.com/Jiyur)
- ⚡️ 优化 Table 筛选搜索性能,复用规范化后的搜索输入。 [#57651](https://github.com/ant-design/ant-design/pull/57651) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Table `rowSelection` 默认未使用 Design Token 中 `selectionColumnWidth` 的问题。 [#57621](https://github.com/ant-design/ant-design/pull/57621) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Design Token 阴影 token 未适配暗色主题的问题。 [#57511](https://github.com/ant-design/ant-design/pull/57511) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Transfer 列表项禁用时移除按钮在悬停下仍会变色的问题。 [#57579](https://github.com/ant-design/ant-design/pull/57579) [@Jiyur](https://github.com/Jiyur)
- 🐞 修复 Tree 父级节点出现多行内容时 checkbox、switcher 和 content 未整体对齐的问题。 [#57471](https://github.com/ant-design/ant-design/pull/57471) [@jiangrong-devops](https://github.com/jiangrong-devops)
## 6.3.5
`2026-03-30`
- 🐞 修复 Image 预览底部操作按钮没有重置原生按钮样式的问题。[#57491](https://github.com/ant-design/ant-design/pull/57491) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 TimePicker 在移动端触摸设备无法直接滚动时间列的问题。[#57468](https://github.com/ant-design/ant-design/pull/57468) [@afc163](https://github.com/afc163)
- 🐞 杂项:修复 Icon 在特定场景没有居中对齐的问题。[#57460](https://github.com/ant-design/ant-design/pull/57460) [@QDyanbing](https://github.com/QDyanbing)
## 6.3.4
`2026-03-24`
- 🔥 新增官方命令行工具 [`@ant-design/cli`](https://www.npmjs.com/package/@ant-design/cli),支持离线查询 Ant Design 组件知识、分析项目用法及提供迁移指导。[#57413](https://github.com/ant-design/ant-design/pull/57413) [@afc163](https://github.com/afc163)
- 🐞 修复 Form.List 在使用 `onValuesChange` 时丢失同级字段值的问题。[#57399](https://github.com/ant-design/ant-design/pull/57399) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 `useToken` 缺少 `screenXXXLMin` 导致生成错误的 antd.css 的问题。[#57372](https://github.com/ant-design/ant-design/pull/57372) [@sealye09](https://github.com/sealye09)
- 🐞 修复 ConfigProvider 组件配置的类型定义,为已支持的组件暴露语义化 `classNames` 和 `styles`。[#57396](https://github.com/ant-design/ant-design/pull/57396) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Image 组件 `fetchPriority` 属性未正确透传到 ` ` 元素的问题。[#57392](https://github.com/ant-design/ant-design/pull/57392) [@aojunhao123](https://github.com/aojunhao123)
- Menu
- 🐞 修复通过 ConfigProvider 自定义 Menu 的 `itemHoverColor` 时,SubMenu 父级菜单项 hover 状态颜色不生效的问题。[#57374](https://github.com/ant-design/ant-design/pull/57374) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Menu 自定义 `collapsedIconSize` 后折叠图标看起来未居中的问题。[#57360](https://github.com/ant-design/ant-design/pull/57360) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Table 在开启滚动时列头中受控 Popover 被重复渲染的问题。[#57342](https://github.com/ant-design/ant-design/pull/57342) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Transfer `render` 属性返回 JSX 元素时搜索功能失效的问题。[#57133](https://github.com/ant-design/ant-design/pull/57133) [@WustLCQ](https://github.com/WustLCQ)
- 🐞 修复 Tree 开启 `showLine` 时自定义 `switcherIcon` 缺少 `switcher-line-icon` 类名导致样式异常的问题。[#57303](https://github.com/ant-design/ant-design/pull/57303) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Watermark 在未传入 `onRemove` 时的 TypeScript 报错。[#57344](https://github.com/ant-design/ant-design/pull/57344) [@QDyanbing](https://github.com/QDyanbing)
## 6.3.3
`2026-03-16`
- Image
- 💄 优化 Image 预览蒙层 blur 效果的 `backdrop-filter` 过渡,减少闪烁感。[#57299](https://github.com/ant-design/ant-design/pull/57299) [@mango766](https://github.com/mango766)
- 🐞 修复 Image 在 `movable={false}` 时仍显示 move 光标的问题。[#57288](https://github.com/ant-design/ant-design/pull/57288) [@ug-hero](https://github.com/ug-hero)
- ⌨️ 优化 App 链接的 `:focus-visible` 外框样式,提升键盘可访问性。[#57266](https://github.com/ant-design/ant-design/pull/57266) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Form 必填标记文案中硬编码 `SimSun` 字体的问题。[#57273](https://github.com/ant-design/ant-design/pull/57273) [@mavericusdev](https://github.com/mavericusdev)
- 🐞 修复 Grid `xxxl` 断点在媒体尺寸映射中的错误。[#57246](https://github.com/ant-design/ant-design/pull/57246) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 Tree 点击节点时页面回滚到顶部的问题。[#57242](https://github.com/ant-design/ant-design/pull/57242) [@aojunhao123](https://github.com/aojunhao123)
## 6.3.2
`2026-03-09`
- 🐞 修复 Form.Item 使用动态 `rules` 与 `dependencies` 配合使用时,时序问题导致的校验失败的问题。[#57147](https://github.com/ant-design/ant-design/pull/57147) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 InputNumber 在 `borderless` 形态下与 Input 或 Select 并排时高度异常的问题。[#57162](https://github.com/ant-design/ant-design/pull/57162) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Radio.Group 在选项文案长短不一或换行时,勾选框宽度不一致的问题。[#57171](https://github.com/ant-design/ant-design/pull/57171) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Skeleton.Avatar,Skeleton.Button,Skeleton.Input,Rate 及 Spin 无法响应全局 `componentSize` 设置的问题。[#57093](https://github.com/ant-design/ant-design/pull/57093) [#57106](https://github.com/ant-design/ant-design/pull/57106) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Splitter 存在 `size` 受控面板时其他面板尺寸可能计算错误的问题。[#57142](https://github.com/ant-design/ant-design/pull/57142) [@js0753](https://github.com/js0753)
- 🐞 修复 Tree 及 TreeSelect 在自定义 `titleHeight` 时会连线错位的问题。[#56785](https://github.com/ant-design/ant-design/pull/56785) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Checkbox.Group 在选项文案长短不一或换行时,勾选框宽度不一致的问题。[#57144](https://github.com/ant-design/ant-design/pull/57144) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 ConfigProvider 的 `csp` 配置没有对所有的动态 style 生效的问题。[#57159](https://github.com/ant-design/ant-design/pull/57159) [@zombieJ](https://github.com/zombieJ)
- Select
- 💄 修复 Select 在 Firefox 浏览器下可能出现文字跳动的问题。[#57030](https://github.com/ant-design/ant-design/pull/57030) [@pierreeurope](https://github.com/pierreeurope)
- 💄 修复 Select 无法通过 `style` 设置 `visibility: hidden` 的问题。[#56720](https://github.com/ant-design/ant-design/pull/56720) [@claytonlin1110](https://github.com/claytonlin1110)
- Upload
- 💄 修复 Upload 在 `picture-card` 模式下无数据时仍然存在无效空白区域的问题。[#57157](https://github.com/ant-design/ant-design/pull/57157) [@QDyanbing](https://github.com/QDyanbing)
- ⌨️ 优化 Upload 在不支持悬停或粗指针的设备上默认显示列表操作按钮。[#57156](https://github.com/ant-design/ant-design/pull/57156) [@Arktomson](https://github.com/Arktomson)
- 🌐 新增 `es_US` 国际化配置。[#57137](https://github.com/ant-design/ant-design/pull/57137) [@yuriidumych-max](https://github.com/yuriidumych-max)
- 🛠 统一 `size` 枚举值定义,针对 Badge、Card、Progress、Steps、Switch 及 Spin 使用 `medium` 替代 `default`,针对 Descriptions 使用 `medium` 和 `large` 替代 `middle` 和 `default`,针对 Table 和 Divider 使用 `medium` 替代 `middle`。[#57127](https://github.com/ant-design/ant-design/pull/57127) [#57106](https://github.com/ant-design/ant-design/pull/57106) [@QDyanbing](https://github.com/QDyanbing)
- 🛠 统一 `size` className 在所有组件元素上的设置值。[#57106](https://github.com/ant-design/ant-design/pull/57106) [@QDyanbing](https://github.com/QDyanbing)
- TypeScript
- 🤖 新增 Upload.Dragger 的泛型支持。[#57103](https://github.com/ant-design/ant-design/pull/57103) [@fnoopv](https://github.com/fnoopv)
- 🤖 修复 Modal `onCancel` 入参不支持 `KeyboardEvent` 类型的问题。[#57048](https://github.com/ant-design/ant-design/pull/57048) [@eureka928](https://github.com/eureka928)
## 6.3.1
`2026-02-24`
- Select
- 🐞 Select 修复 `value` 为空字符串时下拉框高度不正确的问题。[#56976](https://github.com/ant-design/ant-design/pull/56976) [@zombieJ](https://github.com/zombieJ)
- 🐞 Select 修复 `value` 为空字符串时值回显异常的问题。[#56966](https://github.com/ant-design/ant-design/pull/56966) [@luozz1994](https://github.com/luozz1994)
- 🐞 Select & TreeSelect 修复搜索时已选中值文本仍然显示的问题。[#56946](https://github.com/ant-design/ant-design/pull/56946)
- 🐞 TreeSelect 修复多行文本时 Checkbox 被压缩变形的问题。[#56961](https://github.com/ant-design/ant-design/pull/56961) [@luozz1994](https://github.com/luozz1994)
- 🐞 Typography 修复同时开启 `copyable` 和 `ellipsis` 时,悬停复制按钮会触发省略号 tooltip 的问题;修复从复制按钮移回文字后省略号 tooltip 不再出现的问题。[#56855](https://github.com/ant-design/ant-design/pull/56855) [@claytonlin1110](https://github.com/claytonlin1110)
- 🐞 Progress 修复 `status="active"` 时动画溢出的问题。[#56972](https://github.com/ant-design/ant-design/pull/56972) [@aibayanyu20](https://github.com/aibayanyu20)
- 🐞 Upload 修复照片墙模式下文件数量超过一行时列表溢出重叠的问题。[#56945](https://github.com/ant-design/ant-design/pull/56945) [@xbsheng](https://github.com/xbsheng)
- 🐞 Image 修复打开预览时,部分浏览器会出现闪烁的问题。[#56937](https://github.com/ant-design/ant-design/pull/56937) [@zombieJ](https://github.com/zombieJ)
- ⌨️ ♿ 为 Button、Checkbox、Radio、Switch、Segmented 等组件添加 `prefers-reduced-motion` 媒体查询支持,禁用过渡动画以改善无障碍体验。[#56902](https://github.com/ant-design/ant-design/pull/56902) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 Input 修复 `variant="borderless"` 时高度与 Select 不一致的问题。[#57014](https://github.com/ant-design/ant-design/pull/57014) [@njlazzar-su](https://github.com/njlazzar-su)
- 🐞 Modal 修复 `confirm` 方法在 `icon` 为空时布局出现多余空白的问题。[#57024](https://github.com/ant-design/ant-design/pull/57024) [@Arktomson](https://github.com/Arktomson)
- 🐞 Select 组件中的禁用选项添加 `aria-disabled` 属性。[#57049](https://github.com/ant-design/ant-design/pull/57049) [@meet-student](https://github.com/meet-student)
## 6.3.0
`2026-02-10`
- ConfigProvider
- 🆕 ConfigProvider 支持 Modal 和 Drawer 的 `maskClosable` 全局配置。[#56739](https://github.com/ant-design/ant-design/pull/56739) [@luozz1994](https://github.com/luozz1994)
- 🆕 ConfigProvider 支持 DatePicker 和 TimePicker 的 `suffixIcon` 全局配置。[#56709](https://github.com/ant-design/ant-design/pull/56709) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 ConfigProvider 支持 Cascader 的 `expandIcon` 和 `loadingIcon` 全局配置。[#56482](https://github.com/ant-design/ant-design/pull/56482) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 ConfigProvider 支持 Table 的 `scroll` 全局配置。[#56628](https://github.com/ant-design/ant-design/pull/56628) [@Clayton](https://github.com/Clayton)
- 🆕 ConfigProvider 支持配置 App 的 `className` 与 `style`,以及 ColorPicker 的 `arrow` 属性。[#56573](https://github.com/ant-design/ant-design/pull/56573) [@zombieJ](https://github.com/zombieJ)
- 🆕 ConfigProvider 支持 Button 的 `loadingIcon` 全局配置。[#56439](https://github.com/ant-design/ant-design/pull/56439) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 ConfigProvider 支持 `rangePicker.separator` 全局配置。[#56499](https://github.com/ant-design/ant-design/pull/56499) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 ConfigProvider 支持 Form 的 `tooltipIcon` 和 `tooltipProps` 全局配置。[#56372](https://github.com/ant-design/ant-design/pull/56372) [@guoyunhe](https://github.com/guoyunhe)
- Upload
- 🆕 Upload 新增 `classNames.trigger` 和 `styles.trigger` 属性。[#56578](https://github.com/ant-design/ant-design/pull/56578) [@QdabuliuQ](https://github.com/QdabuliuQ)
- 🆕 Upload.Dragger 支持 `onDoubleClick` 事件。[#56579](https://github.com/ant-design/ant-design/pull/56579) [@ug-hero](https://github.com/ug-hero)
- 🐞 Upload 修复 `picture-card` / `picture-circle` 父节点缺少默认高度的问题。[#56864](https://github.com/ant-design/ant-design/pull/56864) [@wanpan11](https://github.com/wanpan11)
- 🆕 Grid 新增 `xxxl`(1920px)断点以适应 FHD 屏幕。[#56825](https://github.com/ant-design/ant-design/pull/56825) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Switch 语义化结构支持 `indicator` 定制。[#56710](https://github.com/ant-design/ant-design/pull/56710) [@zombieJ](https://github.com/zombieJ)
- Button
- 🐞 Button 修复暗色主题下 `color` 的 `hover` 与 `active` 状态颜色相反的问题。[#56872](https://github.com/ant-design/ant-design/pull/56872) [@zombieJ](https://github.com/zombieJ)
- 🐞 Button 修复边框尺寸未跟随 Design Token `lineWidth` 的问题。[#56683](https://github.com/ant-design/ant-design/pull/56683) [@zombieJ](https://github.com/zombieJ)
- Select
- 💄 Select 移除单选模式下额外的 `-content-value` div DOM,优化语义化结构并支持通过 `classNames` 与 `styles` 覆盖。[#56811](https://github.com/ant-design/ant-design/pull/56811) [@zombieJ](https://github.com/zombieJ)
- 🐞 Select 修复 `notFoundContent` 不生效的问题。[#56756](https://github.com/ant-design/ant-design/pull/56756) [@QdabuliuQ](https://github.com/QdabuliuQ)
- Radio
- 🐞 Radio.Group 修复垂直排列时单选项出现多余右边距的问题。[#56909](https://github.com/ant-design/ant-design/pull/56909) [@jany55555](https://github.com/jany55555)
- 💄 Radio 移除 `icon` 子元素 `-inner` DOM 节点以更好适配语义化结构。[#56783](https://github.com/ant-design/ant-design/pull/56783) [@zombieJ](https://github.com/zombieJ)
- 💄 Modal & Drawer 默认关闭蒙层 blur 效果。[#56781](https://github.com/ant-design/ant-design/pull/56781) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 Tooltip & Popover 修复弹出层动画起始位置偏左的问题。[#56887](https://github.com/ant-design/ant-design/pull/56887) [@zombieJ](https://github.com/zombieJ)
- 🐞 List 修复废弃组件配置的颜色相关 token 不生效的问题。[#56913](https://github.com/ant-design/ant-design/pull/56913) [@zombieJ](https://github.com/zombieJ)
- 🛠 Spin 重构 DOM 结构以对齐不同场景,并支持全量语义化结构(Semantic Structure)。[#56852](https://github.com/ant-design/ant-design/pull/56852) [@zombieJ](https://github.com/zombieJ)
- ⌨️ ♿ Icon 为搜索图标 SVG 添加无障碍名称,改善屏幕阅读器支持。[#56521](https://github.com/ant-design/ant-design/pull/56521) [@huangkevin-apr](https://github.com/huangkevin-apr)
- 🐞 Cascader 修复搜索模式下选择选项并关闭时,过滤列表立即还原影响体验的问题。[#56764](https://github.com/ant-design/ant-design/pull/56764) [@zombieJ](https://github.com/zombieJ)
- ⌨️ ♿ Tree 优化无障碍支持。[#56716](https://github.com/ant-design/ant-design/pull/56716) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 ColorPicker 选择块支持语义化结构,并修复 `root` 语义化错误应用到弹出元素的问题。[#56607](https://github.com/ant-design/ant-design/pull/56607) [@zombieJ](https://github.com/zombieJ)
- 💄 Avatar 将 `size` 默认值从 `default` 改为 `medium` 以保持一致性。[#56440](https://github.com/ant-design/ant-design/pull/56440) [@guoyunhe](https://github.com/guoyunhe)
- 💄 Checkbox 移除 `icon` 子元素 `-inner` DOM 节点以更好适配语义化结构。[#56783](https://github.com/ant-design/ant-design/pull/56783) [@zombieJ](https://github.com/zombieJ)
- MISC
- 🐞 MISC: 修复 UMD 版本中 React Compiler 兼容性问题,现已默认关闭。[#56830](https://github.com/ant-design/ant-design/pull/56830) [@zombieJ](https://github.com/zombieJ)
- 🛠 精简 `styles` 和 `classNames` 类型定义,使其更规范。[#56758](https://github.com/ant-design/ant-design/pull/56758) [@crazyair](https://github.com/crazyair)
## 6.2.3
`2026-02-02`
- Button
- 🐞 修复 Button `defaultBg`、`defaultColor`、`defaultHoverColor` 和 `defaultActiveColor` token 不生效的问题。[#56238](https://github.com/ant-design/ant-design/pull/56238) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Button 默认 token 不生效的问题。[#56719](https://github.com/ant-design/ant-design/pull/56719) [@unknowntocka](https://github.com/unknowntocka)
- 🐞 修复 Button `variant="solid"` 在 Space.Compact 中边框显示异常的问题。[#56486](https://github.com/ant-design/ant-design/pull/56486) [@Pareder](https://github.com/Pareder)
- 🐞 修复 Input.TextArea ref 缺少 `nativeElement` 属性的问题。[#56803](https://github.com/ant-design/ant-design/pull/56803) [@smith3816](https://github.com/smith3816)
- 🐞 修复 Flex 使用 `orientation` 时默认 `align` 不生效的问题。[#55950](https://github.com/ant-design/ant-design/pull/55950) [@YingtaoMo](https://github.com/YingtaoMo)
- 🐞 修复 Typography 链接选择器特异性过低导致样式被覆盖的问题。[#56759](https://github.com/ant-design/ant-design/pull/56759) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 ColorPicker HEX 输入框可以输入无效字符的问题。[#56752](https://github.com/ant-design/ant-design/pull/56752) [@treephesians](https://github.com/treephesians)
## 6.2.2
`2026-01-26`
- 🐞 修复被 Typography 包裹的带 href 的 Button 显示错误颜色和 hover 时 outline 闪烁的问题。[#56619](https://github.com/ant-design/ant-design/pull/56619) [@QdabuliuQ](https://github.com/QdabuliuQ)
- 🐞 修复 Button `type="text"` 时组件 Token 不生效的问题。[#56291](https://github.com/ant-design/ant-design/pull/56291) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Popover 内组件被 Form.Item 状态关联影响的问题。[#56728](https://github.com/ant-design/ant-design/pull/56728)
- 🐞 修复 Select 多选时占位符显示异常的问题。[#56675](https://github.com/ant-design/ant-design/pull/56675)
- 💄 修复 Pagination 全局 `fontSize` 变大时各元素上下错位的问题。[#56715](https://github.com/ant-design/ant-design/pull/56715) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Drawer 在 rtl 模式下 dragger 位置错误的样式问题。[#56693](https://github.com/ant-design/ant-design/pull/56693) [@QdabuliuQ](https://github.com/QdabuliuQ)
## 6.2.1
`2026-01-20`
- 🐞 修复 Button 子元素为包含两个中文字符的标签时,原有 `className` 被清空的问题。[#56593](https://github.com/ant-design/ant-design/pull/56593) [@QdabuliuQ](https://github.com/QdabuliuQ)
- 🐞 修复 DatePicker 在设置 `suffixIcon` 为 `null` 后不会更新 DOM 的问题。[#56637](https://github.com/ant-design/ant-design/pull/56637) [@AlanQtten](https://github.com/AlanQtten)
- 🐞 修复 Table 容器设置圆角时,内部内容区域圆角不一致的问题。[#56478](https://github.com/ant-design/ant-design/pull/56478) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Card Body 区域有非预期圆角值的问题。[#56653](https://github.com/ant-design/ant-design/pull/56653) [@ug-hero](https://github.com/ug-hero)
- 💄 杂项:修复 `undefined` 和 `null` 值被注入到 CSS 的问题。[#56636](https://github.com/ant-design/ant-design/pull/56636) [@li-jia-nan](https://github.com/li-jia-nan)
- 💄 杂项:优化所有组件中的 `background` 过渡为 `background-color`。[#56598](https://github.com/ant-design/ant-design/pull/56598) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 优化 Grid 使用 `genCssVar` 方法以生成更加稳定的 CSS 变量名。[#56635](https://github.com/ant-design/ant-design/pull/56635) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 优化 @ant-design/icons 引入方式为独立图标引入,避免被 externals 增加前置依赖。[#56639](https://github.com/ant-design/ant-design/pull/56639) [@ShenHongFei](https://github.com/ShenHongFei)
## 6.2.0
`2026-01-13`
- 🛠 Button、Masonry、Mentions、Select、Space、Splitter、Steps 等组件批量使用 `genCssVar` 方法以生成更加稳定的 css 变量名。[#56562](https://github.com/ant-design/ant-design/pull/56562) [#56559](https://github.com/ant-design/ant-design/pull/56559) [#56557](https://github.com/ant-design/ant-design/pull/56557) [#56555](https://github.com/ant-design/ant-design/pull/56555) [#56550](https://github.com/ant-design/ant-design/pull/56550) [#56547](https://github.com/ant-design/ant-design/pull/56547) [#56546](https://github.com/ant-design/ant-design/pull/56546) [#56529](https://github.com/ant-design/ant-design/pull/56529) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 QRCode 新增 `marginSize` 属性用于展示二维码留白区。[#56569](https://github.com/ant-design/ant-design/pull/56569) [@afc163](https://github.com/afc163)
- 🆕 Tour 新增 `keyboard` 属性以配置键盘操作。[#56581](https://github.com/ant-design/ant-design/pull/56581) [@cactuser-Lu](https://github.com/cactuser-Lu)
- Tooltip
- 🆕 Tooltip 增加 `maxWidth` design token。[#56540](https://github.com/ant-design/ant-design/pull/56540) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Tooltip/Popover/Popconfirm 默认情况下可以通过 ESC 关闭。[#56492](https://github.com/ant-design/ant-design/pull/56492) [@aojunhao123](https://github.com/aojunhao123)
- 🛠 Steps 移除无用的样式。[#56565](https://github.com/ant-design/ant-design/pull/56565) [@li-jia-nan](https://github.com/li-jia-nan)
- 🆕 Form 支持 `tel` 类型校验。[#56533](https://github.com/ant-design/ant-design/pull/56533) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 Badge 在使用 `text` 属性时,`ref` 无效的问题。[#56532](https://github.com/ant-design/ant-design/pull/56532) [@zombieJ](https://github.com/zombieJ)
- 🆕 Calendar 和 DatePicker 的 `locale` 配置现在支持只填充部分内容。[#56376](https://github.com/ant-design/ant-design/pull/56376) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 ConfigProvider 配置 `theme.cssVar` 对图标无效的问题。[#56504](https://github.com/ant-design/ant-design/pull/56504) [@seanparmelee](https://github.com/seanparmelee)
- 🐞 修复 Collapse `items` 语义化属性无效的问题。[#56517](https://github.com/ant-design/ant-design/pull/56517) [@zombieJ](https://github.com/zombieJ)
- Modal
- 🆕 Modal 支持 `focusable.trap` 以配置是否将焦点锁定在 Modal 内部。[#56500](https://github.com/ant-design/ant-design/pull/56500) [@zombieJ](https://github.com/zombieJ)
- 🛠 移除 Modal 无用的 DOM 结构并且优化焦点捕获以防止意外的焦点逃逸到 Modal 外的情况。[#56142](https://github.com/ant-design/ant-design/pull/56142) [@zombieJ](https://github.com/zombieJ)
- ConfigProvider
- 🆕 ConfigProvider 支持 `pagination` 配置 `totalBoundary` 与 `showSizeChanger` 属性。[#56475](https://github.com/ant-design/ant-design/pull/56475) [@chiaweilee](https://github.com/chiaweilee)
- 🆕 ConfigProvider 支持配置 Alert 全局图标。[#56241](https://github.com/ant-design/ant-design/pull/56241) [@guoyunhe](https://github.com/guoyunhe)
- Drawer
- 🆕 Drawer 新增 `focusable` 以配置展开后的焦点行为,支持配置锁定焦点在框内、关闭后是否返回焦点。[#56463](https://github.com/ant-design/ant-design/pull/56463) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Drawer `size` 定义不支持 string 的问题。[#56358](https://github.com/ant-design/ant-design/pull/56358) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Image 嵌套在 Modal 内时,Esc无法顺序关闭。[#56386](https://github.com/ant-design/ant-design/pull/56386) [@aojunhao123](https://github.com/aojunhao123)
- 🆕 Pagination 支持 `size` 属性。[#56009](https://github.com/ant-design/ant-design/pull/56009) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Breadcrumb 支持 `dropdownIcon` 自定义。[#56250](https://github.com/ant-design/ant-design/pull/56250) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Checkbox.Group 支持 `role` 配置。[#56126](https://github.com/ant-design/ant-design/pull/56126) [@Pareder](https://github.com/Pareder)
- 💄 Mentions 修复不同尺寸下 `padding: undefined` 的无效样式。[#56564](https://github.com/ant-design/ant-design/pull/56564) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Select 在 `size="small"` 时,清除按钮位置对齐问题。[#56525](https://github.com/ant-design/ant-design/pull/56525) [@QDyanbing](https://github.com/QDyanbing)
## 6.1.4
`2026-01-05`
- 🐞 修复 Select 配置 `aria-` 属性时,会同时给多个 DOM 添加的问题。[#56451](https://github.com/ant-design/ant-design/pull/56451) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Table 配置 `scroll.y` 属性时,隐藏的测量表头挂载筛选下拉组件并参与事件判断,导致筛选下拉意外关闭的问题。 [#56425](https://github.com/ant-design/ant-design/pull/56425) [@QDyanbing](https://github.com/QDyanbing)
## 6.1.3
`2025-12-29`
- 🐞 修复 Drawer.PurePanel 无法响应鼠标交互的问题。[#56387](https://github.com/ant-design/ant-design/pull/56387) [@wanpan11](https://github.com/wanpan11)
- 🐞 修复 Select options 属性透传至原生 DOM 导致 React 未知属性警告的问题。[#56341](https://github.com/ant-design/ant-design/pull/56341) [@afc163](https://github.com/afc163)
## 6.1.2
`2025-12-24`
- 🐞 修复 Wave 组件水波纹消失的问题,以及 Button 组件在配置 Dropdown 后,点击触发再次 `hover` 时无法立刻显示 Dropdown 的问题。[#56273](https://github.com/ant-design/ant-design/pull/56273) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Form.List 使用 `useWatch` 时,删除项会触发两次渲染,第一次为不正确的中间状态的问题。[#56319](https://github.com/ant-design/ant-design/pull/56319) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Breadcrumb 组件自定义 `itemRender` 时的链接颜色异常的问题。[#56253](https://github.com/ant-design/ant-design/pull/56253) [@guoyunhe](https://github.com/guoyunhe)
- Transfer
- 💄 修复 Transfer 组件在禁用时不存在选择状态样式类的问题。[#56316](https://github.com/ant-design/ant-design/pull/56316) [@zenggpzqbx](https://github.com/zenggpzqbx)
- 🐞 优化 Transfer 组件逻辑,确保优先使用 `disabled` 属性。[#56280](https://github.com/ant-design/ant-design/pull/56280) [#56093](https://github.com/ant-design/ant-design/pull/56093) [@zenggpzqbx](https://github.com/zenggpzqbx)
- Select
- 🐞 修复 Select 组件缺少语义化 DOM 名称的问题。[#56322](https://github.com/ant-design/ant-design/pull/56322) [@seanparmelee](https://github.com/seanparmelee)
- 🐞 修复 Select 组件在搜索状态下鼠标手型样式不对的问题。[#56130](https://github.com/ant-design/ant-design/pull/56130) [@fpsqdb](https://github.com/fpsqdb)
- 🐞 修复 Select 在同时设置 `showSearch` 和 `disabled` 时鼠标样式不为禁用的问题。[#56340](https://github.com/ant-design/ant-design/pull/56340) [@QDyanbing](https://github.com/QDyanbing)
- 💄 修复 Card 组件在使用 Card.Grid 且未设置头部内容时,边框圆角显示异常的问题。[#56214](https://github.com/ant-design/ant-design/pull/56214) [@DDDDD12138](https://github.com/DDDDD12138)
- 💄 Tag 加深默认背景,提升无边框状态的对比度。[#56326](https://github.com/ant-design/ant-design/pull/56326) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Segmented 组件中多余的 `role` 属性和 `aria` 属性。[#56278](https://github.com/ant-design/ant-design/pull/56278) [@aojunhao123](https://github.com/aojunhao123)
## 6.1.1
`2025-12-15`
- 🐞 修复 DatePicker 不兼容 webpack 4 的问题:Can't resolve '@rc-component/picker/locale/en_US'。[#56219](https://github.com/ant-design/ant-design/pull/56219) [@afc163](https://github.com/afc163)
- 🐞 修复 ColorPicker 弹层内输入框高度不一致问题。[#56220](https://github.com/ant-design/ant-design/pull/56220) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 notification 在 cssVar 未启用时默认背景色不为白色的问题。[#56169](https://github.com/ant-design/ant-design/pull/56169) [@wanpan11](https://github.com/wanpan11)
- 🐞 修复 Input 在 Space.Compact 下配置 `allowClear` 时聚焦边框丢失的问题。[#56105](https://github.com/ant-design/ant-design/pull/56105) [@tuzixiangs](https://github.com/tuzixiangs)
- 🐞 修复 Splitter 在 RTL + 垂直模式下折叠方向错误的问题,RTL 逻辑现在仅在横向布局下生效。[#56179](https://github.com/ant-design/ant-design/pull/56179) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 修复 Result 未向根节点透传 `data-*` 与 `aria-*` 属性的问题。[#56165](https://github.com/ant-design/ant-design/pull/56165) [@QDyanbing](https://github.com/QDyanbing)
- 🐞 MISC: 修复:`theme.cssVar.prefix` 与 `theme.cssVar.key` 不支持传入空字符串的问题。[#56146](https://github.com/ant-design/ant-design/pull/56146) [@QDyanbing](https://github.com/QDyanbing)
- 💄 提升 Breadcrumb 链接样式优先级以避免被全局样式覆盖。[#56137](https://github.com/ant-design/ant-design/pull/56137) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 ConfigProvider `closable.placement` 配置失效的问题。[#55985](https://github.com/ant-design/ant-design/pull/55985) [@meet-student](https://github.com/meet-student)
- 🐞 修复 Form `onValuesChange` 对存在嵌套数据的 Form.List 缺失内容的问题。[#56129](https://github.com/ant-design/ant-design/pull/56129) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Select `selectorBg` token 不生效的问题。[#56052](https://github.com/ant-design/ant-design/pull/56052) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Upload 进度条位置样式错误的问题。[#56194](https://github.com/ant-design/ant-design/pull/56194) [@QDyanbing](https://github.com/QDyanbing)
## 6.1.0
`2025-12-08`
- 🆕 ConfigProvider 新增支持配置 Tooltip、Popover 和 Popconfirm 的 `trigger` 属性。[#55932](https://github.com/ant-design/ant-design/pull/55932) [@aojunhao123](https://github.com/aojunhao123)
- 🆕 Alert 新增语义化关闭按钮元素。[#55815](https://github.com/ant-design/ant-design/pull/55815) [@coding-ice](https://github.com/coding-ice)
- Drawer
- 🆕 Drawer 新增语义化关闭按钮元素。[#55816](https://github.com/ant-design/ant-design/pull/55816) [@coding-ice](https://github.com/coding-ice)
- 🆕 Drawer 新增 `resizable`的布尔类型设置。[#55861](https://github.com/ant-design/ant-design/pull/55861) [@cactuser-Lu](https://github.com/cactuser-Lu)
- Select
- 🆕 Select 新增 `optionFilterProp` 多字段搜索。[#56057](https://github.com/ant-design/ant-design/pull/56057) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Select 非搜索状态下显示输入光标的问题。[#56067](https://github.com/ant-design/ant-design/pull/56067) [@afc163](https://github.com/afc163)
- 🐞 修复 Select 包含交互内容时「选择」选项未打开的问题。[#56054](https://github.com/ant-design/ant-design/pull/56054) [@yoyo837](https://github.com/yoyo837)
- 🐞 修复 Table `cellFontSizeSM` 和 `cellFontSizeLG` token 不生效的问题。[#55770](https://github.com/ant-design/ant-design/pull/55770) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 修复 Button 部分 Token(primaryColor, dangerColor, defaultHoverBg, defaultActiveBg)在特定变体(solid, outlined, dashed)下不生效的问题。[#55934](https://github.com/ant-design/ant-design/pull/55934) [@tuzixiangs](https://github.com/tuzixiangs)
- 💄 修复 Menu 组件 item 中定义的 style 不生效错误。[#56041](https://github.com/ant-design/ant-design/pull/56041) [@Wxh16144](https://github.com/Wxh16144)
- 🛠 杂项:更新 `@ant-design/react-slick` 版本以删除 `classnames`。[#56080](https://github.com/ant-design/ant-design/pull/56080) [@yoyo837](https://github.com/yoyo837)
- 🛠 杂项:迁移 `rc-overflow` 到 `@rc-component/overflow`、`rc-virtual-list` 到 `@rc-component/virtual-list` 以删除 `rc-util`。[#56074](https://github.com/ant-design/ant-design/pull/56074) [@yoyo837](https://github.com/yoyo837)
- TypeScript
- 🤖 Alert 新增导出 ErrorBoundaryProps 类型。[#55974](https://github.com/ant-design/ant-design/pull/55974) [@guoyunhe](https://github.com/guoyunhe)
- 🤖 ConfigProvider 支持 Table `rowKey` 传入函数。[#56095](https://github.com/ant-design/ant-design/pull/56095) [@li-jia-nan](https://github.com/li-jia-nan)
- 🤖 Notification `title` 属性修改为可选。[#56027](https://github.com/ant-design/ant-design/pull/56027) [@afc163](https://github.com/afc163)
## 6.0.1
`2025-12-02`
- Flex
- 🐞 修复 Flex 的 `flex` 属性不能设置为 `0` 的问题。[#55829](https://github.com/ant-design/ant-design/pull/55829) [@li-jia-nan](https://github.com/li-jia-nan)
- 🐞 修复 Flex 的 `gap` 属性不能设置为 `0` 的问题。[#55803](https://github.com/ant-design/ant-design/pull/55803) [@li-jia-nan](https://github.com/li-jia-nan)
- Input
- 🐞 修复 Input `colorText` token 在无前后缀的 `filled` 变体下不工作的问题。[#56019](https://github.com/ant-design/ant-design/pull/56019) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 Input.OTP 在输入时可跳过空位的问题。[#56001](https://github.com/ant-design/ant-design/pull/56001) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 修复 Anchor 快速点击同一链接时的滚动问题。[#55814](https://github.com/ant-design/ant-design/pull/55814) [@tuzixiangs](https://github.com/tuzixiangs)
- 🐞 修复 Button 在 `solid` 变体下悬浮态的文字颜色。[#55825](https://github.com/ant-design/ant-design/pull/55825) [@andriib-ship-it](https://github.com/andriib-ship-it)
- 🐞 修复 Cascader 使用 defaultValue 时首次打开会滚动到页面顶部的问题。[#55890](https://github.com/ant-design/ant-design/pull/55890) [@tuzixiangs](https://github.com/tuzixiangs)
- 🐞 修复 DatePicker `borderRadiusSM` 和 `borderRadiusLG` token 未生效问题。[#56018](https://github.com/ant-design/ant-design/pull/56018) [@ug-hero](https://github.com/ug-hero)
- 🐞 修复 InputNumber 在 ColorPicker 中使用时文字被裁切的问题。[#55966](https://github.com/ant-design/ant-design/pull/55966) [@DDDDD12138](https://github.com/DDDDD12138)
- 🐞 修复 Select 在深色模式下的搜索框文本颜色。[#55914](https://github.com/ant-design/ant-design/pull/55914) [@divyeshagrawal](https://github.com/divyeshagrawal)
- 🐞 修复 Splitter 在 Panel 总占比不为 1 时出现占不满的情况。 [#56025](https://github.com/ant-design/ant-design/pull/56025) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Wave 可能由于 RAF 未清理引发内存泄露的风险。[#55962](https://github.com/ant-design/ant-design/pull/55962) [@Copilot](https://github.com/Copilot)
- 🐞 修复 Modal/Image/Drawer 组件 `colorBgMask` token 不生效的问题。[#56031](https://github.com/ant-design/ant-design/pull/56031) [@ug-hero](https://github.com/ug-hero)
- 💄 修复 ConfigProvider 默认没有配置 `theme.hashed` 为 `true`,从而会导致多版本混用样式冲突的问题。[#55880](https://github.com/ant-design/ant-design/pull/55880) [@zombieJ](https://github.com/zombieJ)
- 💄 修复 Layout.Sider 在 zeroRuntime 开启时样式缺失的问题。[#55864](https://github.com/ant-design/ant-design/pull/55864) [@wanpan11](https://github.com/wanpan11)
- 🛠 杂项:修复版本无法在 pnpm `hoist: false` 下通过 vite 编译。[#55938](https://github.com/ant-design/ant-design/pull/55938) [@afc163](https://github.com/afc163)
- TypeScript
- 🤖 修复 ConfigProvider 的 Table `classNames` 及 `styles` 配置类型缺失的问题。[#55984](https://github.com/ant-design/ant-design/pull/55984) [@meet-student](https://github.com/meet-student)
- 🤖 修复 DatePicker 多个属性的类型定义。[#55826](https://github.com/ant-design/ant-design/pull/55826) [@divyeshagrawal](https://github.com/divyeshagrawal)
## 6.0.0
`2025-11-22`
🏆 Ant Design 6.0.0 已发布!
#### 升级必读
🌟 如果你想升级到 Ant Design 6.0,请仔细查阅我们的[迁移文档](/docs/react/migration-v6-cn)。
#### 主要变化
- 🔥 组件语义化结构,阅读[《语义化发现组件精致的美》](/docs/blog/semantic-beauty-cn)了解更多。
🔥 antd 组件支持语义化结构以及 ConfigProvider 配置,由 @thinkasany 主导。
- feat(Result): support `classNames` and `styles` for component and ConfigProvider [#52171](https://github.com/ant-design/ant-design/pull/52171)
- feat(Statistic): support `classNames` and `styles` for component and ConfigProvider [#52141](https://github.com/ant-design/ant-design/pull/52141)
- feat(Collapse): support `classNames` and `styles` for component and ConfigProvider [#52258](https://github.com/ant-design/ant-design/pull/52258)
- feat(Badge.Ribbon): support ConfigProvider [#52303](https://github.com/ant-design/ant-design/pull/52303)
- feat(Segmented): support `classNames` and `styles` for component and ConfigProvider [#52376](https://github.com/ant-design/ant-design/pull/52376)
- feat(Modal): support `classNames` and `styles` for component and ConfigProvider [#52340](https://github.com/ant-design/ant-design/pull/52340)
- feat(Alert): support `classNames` and `styles` for component and ConfigProvider [#52669](https://github.com/ant-design/ant-design/pull/52669)
- feat(Skeleton): support `classNames` and `styles` [#52470](https://github.com/ant-design/ant-design/pull/52470) [@coding-ice](https://github.com/coding-ice)
- feat(Notification): support `classNames` and `styles` for component and ConfigProvider [#52759](https://github.com/ant-design/ant-design/pull/52759)
- feat(Tag): support `classNames` and `styles` for component and ConfigProvider [#52764](https://github.com/ant-design/ant-design/pull/52764)
- feat(Affix): support `classNames` and `styles` for component and ConfigProvider [#52745](https://github.com/ant-design/ant-design/pull/52745)
- feat(Checkbox): support `classNames` and `styles` for component and ConfigProvider [#52781](https://github.com/ant-design/ant-design/pull/52781)
- feat(Radio): support `classNames` and `styles` for component and ConfigProvider [#52780](https://github.com/ant-design/ant-design/pull/52780)
- feat(Message): support `classNames` and `styles` for component and ConfigProvider [#52793](https://github.com/ant-design/ant-design/pull/52793)
- feat(Watermark): support `classNames` and `styles` for component and ConfigProvider [#52811](https://github.com/ant-design/ant-design/pull/52811)
- feat(Spin): support `classNames` and `styles` for component and ConfigProvider [#52823](https://github.com/ant-design/ant-design/pull/52823)
- feat(Switch): support `classNames` and `styles` for component and ConfigProvider [#52849](https://github.com/ant-design/ant-design/pull/52849)
- feat(Breadcrumb): support `classNames` and `styles` for component and ConfigProvider [#52859](https://github.com/ant-design/ant-design/pull/52859)
- feat(Anchor): support `classNames` and `styles` for component and ConfigProvider [#52866](https://github.com/ant-design/ant-design/pull/52866)
- feat(Pagination): support `classNames` and `styles` for component and ConfigProvider [#52893](https://github.com/ant-design/ant-design/pull/52893)
- feat(Tabs): support `classNames` and `styles` for component and ConfigProvider [#52895](https://github.com/ant-design/ant-design/pull/52895)
- feat(Timeline): support `classNames` and `styles` for component and ConfigProvider [#52976](https://github.com/ant-design/ant-design/pull/52976)
- feat(Mentions): support `classNames` and `styles` for component and ConfigProvider [#52961](https://github.com/ant-design/ant-design/pull/52961)
- feat(Upload): support `classNames` and `styles` for component and ConfigProvider [#52972](https://github.com/ant-design/ant-design/pull/52972)
- feat(Tour): support ConfigProvider [#52250](https://github.com/ant-design/ant-design/pull/52250)
- feat(Button): support `classNames` and `styles` for component and ConfigProvider [#53055](https://github.com/ant-design/ant-design/pull/53055)
- feat(Select): support `classNames` and `styles` for component and ConfigProvider [#52948](https://github.com/ant-design/ant-design/pull/52948)
- feat(Image): support `classNames` and `styles` for component and ConfigProvider [#53028](https://github.com/ant-design/ant-design/pull/53028)
- feat(Tree): support `classNames` and `styles` for component and ConfigProvider [#53174](https://github.com/ant-design/ant-design/pull/53174)
- feat(AutoComplete): support `classNames` and `styles` for component and ConfigProvider [#53150](https://github.com/ant-design/ant-design/pull/53150)
- feat(Splitter): support `classNames` and `styles` [#53225](https://github.com/ant-design/ant-design/pull/53225) [@wanpan11](https://github.com/wanpan11)
- feat(Form): support `classNames` and `styles` for component and ConfigProvider [#53226](https://github.com/ant-design/ant-design/pull/53226)
- feat(Calendar): support `classNames` and `styles` for component and ConfigProvider [#53159](https://github.com/ant-design/ant-design/pull/53159)
- feat(TreeSelect): support `classNames` and `styles` for component and ConfigProvider [#53229](https://github.com/ant-design/ant-design/pull/53229)
- feat(ColorPicker): support `classNames` and `styles` for component and ConfigProvider [#53303](https://github.com/ant-design/ant-design/pull/53303)
- feat(Transfer): support `classNames` and `styles` for component and ConfigProvider [#53429](https://github.com/ant-design/ant-design/pull/53429) [@zombieJ](https://github.com/zombieJ)
- feat(QRCode): support ConfigProvider [#52172](https://github.com/ant-design/ant-design/pull/52172)
- feat(Progress): support `classNames` and `styles` for component and ConfigProvider [#53535](https://github.com/ant-design/ant-design/pull/53535) [@zombieJ](https://github.com/zombieJ)
- feat(TimePicker, DatePicker): support `classNames` and `styles` for components and ConfigProvider [#53489](https://github.com/ant-design/ant-design/pull/53489)
- feat(Menu): support `classNames` and `styles` for component and ConfigProvider [#53324](https://github.com/ant-design/ant-design/pull/53324)
- feat(Dropdown): support `classNames` and `styles` for component and ConfigProvider [#53272](https://github.com/ant-design/ant-design/pull/53272)
- feat(Cascader): support `classNames` and `styles` for component and ConfigProvider [#53694](https://github.com/ant-design/ant-design/pull/53694)
- feat(InputNumber): support `classNames` and `styles` for component and ConfigProvider [#53698](https://github.com/ant-design/ant-design/pull/53698)
- feat(Steps): support `classNames` and `styles` for component and ConfigProvider [#53789](https://github.com/ant-design/ant-design/pull/53789) [@zombieJ](https://github.com/zombieJ)
- feat(Table): support `classNames` and `styles` for component and ConfigProvider [#53659](https://github.com/ant-design/ant-design/pull/53659)
- feat(Divider): support `classNames` and `styles` for component and ConfigProvider [#53890](https://github.com/ant-design/ant-design/pull/53890)
- feat(Input): support semantic DOM [#53958](https://github.com/ant-design/ant-design/pull/53958) [@aojunhao123](https://github.com/aojunhao123)
- feat(FloatButton): support semantic structure and support ConfigProvider to pass related props [#54145](https://github.com/ant-design/ant-design/pull/54145) [@zombieJ](https://github.com/zombieJ)
- refactor(Select): support semantic structure [#55430](https://github.com/ant-design/ant-design/pull/55430) [@zombieJ](https://github.com/zombieJ)
🔥 antd 组件支持通过函数动态生成语义化结构,由 @meet-student 主导。
- feat(button): Support better customization with semantic classNames/styles as function [#54813](https://github.com/ant-design/ant-design/pull/54813)
- feat(input): Support better customization with semantic classNames/styles as function [#54919](https://github.com/ant-design/ant-design/pull/54919)
- feat(float-button): Support better customization with semantic classNames/styles as function [#54917](https://github.com/ant-design/ant-design/pull/54917)
- feat(divider): Support better customization with semantic classNames/styles as function [#54949](https://github.com/ant-design/ant-design/pull/54949)
- feat(breadcrumb): Support better customization with semantic classNames/styles as function [#54950](https://github.com/ant-design/ant-design/pull/54950)
- feat(anchor): Support better customization with semantic classNames/styles as function [#54948](https://github.com/ant-design/ant-design/pull/54948)
- feat(masonry): Support better customization with semantic classNames/styles as function [#55032](https://github.com/ant-design/ant-design/pull/55032)
- feat(Progress): Support better customization with semantic classNames & styles [#55058](https://github.com/ant-design/ant-design/pull/55058) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(menu): Support better customization with semantic classNames/styles as function [#54955](https://github.com/ant-design/ant-design/pull/54955)
- feat(space): Support better customization with semantic classNames/styles as function [#55031](https://github.com/ant-design/ant-design/pull/55031) [@hcjlxl](https://github.com/hcjlxl)
- feat(tabs): Support better customization with semantic classNames/styles as function [#54958](https://github.com/ant-design/ant-design/pull/54958)
- feat(splitter): Support better customization with semantic classNames/styles as function [#55013](https://github.com/ant-design/ant-design/pull/55013) [@hcjlxl](https://github.com/hcjlxl)
- feat(pagination): Support better customization with semantic classNames/styles as function [#54957](https://github.com/ant-design/ant-design/pull/54957)
- feat(steps): Support better customization with semantic classNames/styles as function [#54956](https://github.com/ant-design/ant-design/pull/54956)
- feat(dropdown): Support better customization with semantic classNames/styles as function [#55114](https://github.com/ant-design/ant-design/pull/55114) [@Arktomson](https://github.com/Arktomson)
- feat(checkbox_radio): Support better customization with semantic classNames/styles as function [#55056](https://github.com/ant-design/ant-design/pull/55056)
- feat(auto-complete): Support better customization with semantic classNames/styles as function [#54959](https://github.com/ant-design/ant-design/pull/54959)
- feat(form): Support better customization with semantic classNames/styles as function [#55126](https://github.com/ant-design/ant-design/pull/55126)
- feat(date-picker_time-picker): Support better customization with semantic classNames/styles as function [#54969](https://github.com/ant-design/ant-design/pull/54969)
- feat(InputNumber): Support better customization with semantic classNames/styles as function [#54996](https://github.com/ant-design/ant-design/pull/54996) [@zjr222](https://github.com/zjr222)
- feat(input-otp_textarea_search): Support better customization with semantic classNames/styles as function [#55109](https://github.com/ant-design/ant-design/pull/55109) [@Arktomson](https://github.com/Arktomson)
- feat(mentions): Support better customization with semantic classNames/styles as function [#54963](https://github.com/ant-design/ant-design/pull/54963)
- feat(select): Support better customization with semantic classNames/styles as function [#55101](https://github.com/ant-design/ant-design/pull/55101) [@Linkodt](https://github.com/Linkodt)
- feat(slider): Support better customization with semantic classNames/styles as function [#54965](https://github.com/ant-design/ant-design/pull/54965)
- feat(switch): Support better customization with semantic classNames/styles as function [#54994](https://github.com/ant-design/ant-design/pull/54994) [@xkhanhan](https://github.com/xkhanhan)
- feat(transfer): Support better customization with semantic classNames/styles as function [#54966](https://github.com/ant-design/ant-design/pull/54966)
- feat(upload): Support better customization with semantic classNames/styles as function [#54968](https://github.com/ant-design/ant-design/pull/54968)
- feat(calendar): Support better customization with semantic classNames/styles as function [#54978](https://github.com/ant-design/ant-design/pull/54978)
- feat(descriptions): Support better customization with semantic classNames/styles [#55118](https://github.com/ant-design/ant-design/pull/55118) [@tanjiahao24](https://github.com/tanjiahao24)
- feat(empty): Support better customization with semantic classNames/styles as function [#55007](https://github.com/ant-design/ant-design/pull/55007) [@Susuperli](https://github.com/Susuperli)
- refactor: semantic of Descriptions [#55190](https://github.com/ant-design/ant-design/pull/55190)
- feat(qr-code): Support better customization with semantic classNames/styles as function [#54982](https://github.com/ant-design/ant-design/pull/54982)
- feat(statistic): Support better customization with semantic classNames/styles as function [#55117](https://github.com/ant-design/ant-design/pull/55117) [@Arktomson](https://github.com/Arktomson)
- feat(table): Support better customization with semantic classNames/styles as function [#54983](https://github.com/ant-design/ant-design/pull/54983)
- feat(tag): Support better customization with semantic classNames/styles as function [#54984](https://github.com/ant-design/ant-design/pull/54984)
- feat(alert): Support better customization with semantic classNames/styles [#55060](https://github.com/ant-design/ant-design/pull/55060) [@ccc1018](https://github.com/ccc1018)
- feat(result): Support better customization with semantic classNames/styles as function [#55044](https://github.com/ant-design/ant-design/pull/55044) [@ccc1018](https://github.com/ccc1018)
- feat(Drawer): Support better customization with semantic classNames & styles [#55096](https://github.com/ant-design/ant-design/pull/55096) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(Modal): Support better customization with semantic classNames & styles [#55081](https://github.com/ant-design/ant-design/pull/55081) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(notification): Support better customization with semantic classNames/styles as function [#55021](https://github.com/ant-design/ant-design/pull/55021) [@GinWU05](https://github.com/GinWU05)
- feat(spin): Support better customization with semantic classNames/styles as function [#55157](https://github.com/ant-design/ant-design/pull/55157) [@Susuperli](https://github.com/Susuperli)
- feat(card): Support better customization with semantic classNames/styles as function [#55161](https://github.com/ant-design/ant-design/pull/55161) [@lovelts](https://github.com/lovelts)
- feat(collapse): Support better customization with semantic classNames/styles as function [#54979](https://github.com/ant-design/ant-design/pull/54979)
- feat(message): support better customization with semantic classNames/styles [#55054](https://github.com/ant-design/ant-design/pull/55054) [@nmsn](https://github.com/nmsn)
- feat(image): Support better customization with semantic classNames/styles as function [#54980](https://github.com/ant-design/ant-design/pull/54980)
- feat(segmented): Support better customization with semantic classNames/styles as function [#55119](https://github.com/ant-design/ant-design/pull/55119) [@Arktomson](https://github.com/Arktomson)
- feat(timeline): Support better customization with semantic classNames/styles as function [#54985](https://github.com/ant-design/ant-design/pull/54985)
- refactor: semantic of message and notification [#55199](https://github.com/ant-design/ant-design/pull/55199)
- feat(tour): Support better customization with semantic classNames/styles as function [#54987](https://github.com/ant-design/ant-design/pull/54987)
- feat(tree): Support better customization with semantic classNames/styles as function [#54988](https://github.com/ant-design/ant-design/pull/54988)
- feat(Popover/Tooltip/Popconfirm): Support better customization with semantic classNames/styles as function [#54986](https://github.com/ant-design/ant-design/pull/54986)
- feat(Skeleton): Support better customization with semantic classNames & styles [#55099](https://github.com/ant-design/ant-design/pull/55099) [@li-jia-nan](https://github.com/li-jia-nan)
- feat(cascader): Support better customization with semantic classNames/styles as function [#54960](https://github.com/ant-design/ant-design/pull/54960)
- feat(color-picker): Support better customization with semantic classNames/styles as function [#54962](https://github.com/ant-design/ant-design/pull/54962)
- feat(badge): Support better customization with semantic classNames/styles as function [#54977](https://github.com/ant-design/ant-design/pull/54977)
- feat(tree-select): Support better customization with semantic classNames/styles as function [#54967](https://github.com/ant-design/ant-design/pull/54967)
- feat(CheckableTagGroup): Support better customization with semantic classNames/styles as function [#55796](https://github.com/ant-design/ant-design/pull/55796)
- 🔥 新增 Masonry 瀑布流组件。[#52162](https://github.com/ant-design/ant-design/pull/52162) [@OysterD3](https://github.com/OysterD3)
- ConfigProvider
- 🆕 ConfigProvider 支持 Table `rowKey` 全局配置。[#52751](https://github.com/ant-design/ant-design/pull/52751) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 ConfigProvider 支持 Card.Meta 的配置。[#52214](https://github.com/ant-design/ant-design/pull/52214) [@thinkasany](https://github.com/thinkasany)
- 🆕 ConfigProvider 支持Tooltip / Popover / Popconfirm 组件的箭头配置。[#52434](https://github.com/ant-design/ant-design/pull/52434) [@thinkasany](https://github.com/thinkasany)
- 🆕 ConfigProvider 支持 Space 组件 `root` 配置。[#52248](https://github.com/ant-design/ant-design/pull/52248) [@thinkasany](https://github.com/thinkasany)
- Tooltip
- 🔥 ConfigProvider 支持配置 `tooltip.unique` 让 Tooltip 支持平滑移动。[#55154](https://github.com/ant-design/ant-design/pull/55154) [@zombieJ](https://github.com/zombieJ)
- ⚡️ 优化 Tooltip 开发模式下性能(约 ~40%)以提升研发体验。[#53844](https://github.com/ant-design/ant-design/pull/53844) [@zombieJ](https://github.com/zombieJ)
- Input
- 🔥 InputNumber 增加 `mode="spinner"` 拨轮模式。[#55592](https://github.com/ant-design/ant-design/pull/55592) [@guoyunhe](https://github.com/guoyunhe)
- 🗑 Input.Search 重构废弃内部 `addon*` 的使用,用 Space.Compact 替换。[#55705](https://github.com/ant-design/ant-design/pull/55705) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Input.TextArea 的 `styles.textarea` 无法覆盖内置样式的问题。[#55579](https://github.com/ant-design/ant-design/pull/55579) [@meet-student](https://github.com/meet-student)
- 🆕 Pagination 快速跳转输入框现在限制只能输入数字。[#55700](https://github.com/ant-design/ant-design/pull/55700) [@afc163](https://github.com/afc163)
- Mentions
- 🛠 重构 Mentions DOM 结构并支持 `suffix` 语义化结构以及 `size` 属性。[#55638](https://github.com/ant-design/ant-design/pull/55638) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Mentions 的 `autoResize=false` 时,无法拖拽缩放尺寸的问题。[#54039](https://github.com/ant-design/ant-design/pull/54039) [@jin19980928](https://github.com/jin19980928)
- 🆕 Watermark 新增 `onRemove` 以支持被用户手工删除的事件触发。[#55551](https://github.com/ant-design/ant-design/pull/55551) [@984507092](https://github.com/984507092)
- 🆕 Breadcrumb 支持 ConfigProvider `separator` 全局配置。[#54680](https://github.com/ant-design/ant-design/pull/54680) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Alert `closable` 支持 onClose 和 afterClose 方法。[#54735](https://github.com/ant-design/ant-design/pull/54735) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Radio.Group 支持 `vertical` 纵向排列语法糖。[#54727](https://github.com/ant-design/ant-design/pull/54727) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- Cascader
- 🆕 Cascader 支持 `aria-*` 和 `data-*` 属性。[#53910](https://github.com/ant-design/ant-design/pull/53910) [@kiner-tang](https://github.com/kiner-tang)
- 🆕 Cascader.Panel 添加 optionRender 允许自定义渲染选项。[#54843](https://github.com/ant-design/ant-design/pull/54843) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Upload `accept` 配置支持自定义过滤逻辑。[#55543](https://github.com/ant-design/ant-design/pull/55543) [@zombieJ](https://github.com/zombieJ)
- Rate
- 🆕 Rate 支持 `size` 以配置大小。[#55028](https://github.com/ant-design/ant-design/pull/55028) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Rate `tooltips` 支持所有的提示属性配置。[07b1610](https://github.com/ant-design/ant-design/commit/07b1610) [@Jerryqun](https://github.com/Jerryqun)
- 🆕 Select 支持键盘和鼠标交互时 `onActive` 回调。[#53931](https://github.com/ant-design/ant-design/pull/53931) [@Wxh16144](https://github.com/Wxh16144)
- 🆕 Typography `copyable` 支持 HTTP 环境。[#55073](https://github.com/ant-design/ant-design/pull/55073) [@JeeekXY](https://github.com/JeeekXY)
- Form
- 🔥 Form `useWatch` 支持动态更改监听字段名称。[#54260](https://github.com/ant-design/ant-design/pull/54260) [@zombieJ](https://github.com/zombieJ)
- 🆕 Form 现在取值会排除 `Form.List` 中未被注册的字段值。[#55526](https://github.com/ant-design/ant-design/pull/55526) [@crazyair](https://github.com/crazyair)
- ⚡️ 优化 Form 在大量字段卸载时 `useWatch` 的性能。[#54212](https://github.com/ant-design/ant-design/pull/54212) [@zombieJ](https://github.com/zombieJ)
- 🆕 Flex 增加 `orientation` 属性用于布局,原 `vertical` 语法糖仍然保留。[#53648](https://github.com/ant-design/ant-design/pull/53648) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- DatePicker
- 🆕 DatePicker 语义化结构新增面板 `container` 支持。[#55388](https://github.com/ant-design/ant-design/pull/55388) [@meet-student](https://github.com/meet-student)
- 🆕 DatePicker 新增 `previewValue` ,以控制鼠标悬停在选项时是否输入框展示预览值。[#55258](https://github.com/ant-design/ant-design/pull/55258) [@meet-student](https://github.com/meet-student)
- 🐞 修复 DatePicker 在清空时,`onChange` 参数 `dateString` 返回值错误的问题。[#55155](https://github.com/ant-design/ant-design/pull/55155) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- Drawer
- 🆕 Drawer 新增 `resizable` 支持拖拽能力。[#54883](https://github.com/ant-design/ant-design/pull/54883) [@cactuser-Lu](https://github.com/cactuser-Lu)
- 💄 Drawer 遮罩添加模糊效果。[#54707](https://github.com/ant-design/ant-design/pull/54707) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 ColorPicker `presets` 支持渐变色预设值。[#53250](https://github.com/ant-design/ant-design/pull/53250) [@zombieJ](https://github.com/zombieJ)
- Collapse
- 🆕 Collapse `expandIconPosition` 替换为`expandIconPlacement`,并使用逻辑位置以优化 RTL 体验。[#54311](https://github.com/ant-design/ant-design/pull/54311) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Collapse 语义化结构 `icon` 作用元素不正确的问题。[#55499](https://github.com/ant-design/ant-design/pull/55499) [@thinkasany](https://github.com/thinkasany)
- 🐞 修复 Collapse 动态修改语义化 icon 不生效的问题。[#55452](https://github.com/ant-design/ant-design/pull/55452) [@thinkasany](https://github.com/thinkasany)
- Table
- 🆕 Table `scrollTo` 方法支持 `offset` 以设置滚动偏移量。[#54385](https://github.com/ant-design/ant-design/pull/54385) [@zombieJ](https://github.com/zombieJ)
- 🆕 Table `pagination.position` 替换为 `pagination.placement`。[#54338](https://github.com/ant-design/ant-design/pull/54338) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- ⌨️ ⌨️ 优化 Table `column` 为 `sortable` 时的 `aria-description` 可访问性属性。[#53087](https://github.com/ant-design/ant-design/pull/53087) [@jon-cullison](https://github.com/jon-cullison)
- 🆕 重构 Table `column.fixed` 用 `start` 和 `end` 的逻辑位置以支持 RTL。[#53114](https://github.com/ant-design/ant-design/pull/53114) [@zombieJ](https://github.com/zombieJ)
- 🐞 修复 Table 在使用 `sticky` 或 `scroll.y` 时出现重复的筛选下拉框和提示气泡显示的问题。修复 Table 渲染初始阶段列头不显示的问题。[#54910](https://github.com/ant-design/ant-design/pull/54910) [@afc163](https://github.com/afc163)
- 🐞 修复 Table 在动态修改 `childrenColumnName` 时,数据不会刷新的问题。[#55559](https://github.com/ant-design/ant-design/pull/55559) [@li-jia-nan](https://github.com/li-jia-nan)
- Progress
- 🆕 Progress `gapPosition` 替换为 `gapPlacement`,并使用位置描述值 `start` 和 `end` 取代 `left` 和 `right`。[#54329](https://github.com/ant-design/ant-design/pull/54329) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Progress 在变更 props 时,指示内容不会更新的问题。[#55554](https://github.com/ant-design/ant-design/pull/55554) [@thinkasany](https://github.com/thinkasany)
- 🛠 Grid 使用 CSS 逻辑位置以支持 RTL 体验。[#52560](https://github.com/ant-design/ant-design/pull/52560) [@li-jia-nan](https://github.com/li-jia-nan)
- Notification
- 🛠 Notification 提供 `closable` 属性将 `onClose` 与 `closeIcon` 收敛至其中。[#54645](https://github.com/ant-design/ant-design/pull/54645) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Notification 支持自定义进度条颜色。[#52964](https://github.com/ant-design/ant-design/pull/52964) [@yellowryan](https://github.com/yellowryan)
- 🆕 Notification 新增 `title` 属性用以替代 `message` 属性,同时废弃 `message` 属性。[#52759](https://github.com/ant-design/ant-design/pull/52759) [@thinkasany](https://github.com/thinkasany)
- Image
- 🆕 Image 的预览遮罩 `cover` 支持设置遮罩位置。[#54492](https://github.com/ant-design/ant-design/pull/54492) [@kiner-tang](https://github.com/kiner-tang)
- 🛠 Image 移除默认的查看图标和文案(仍然可以通过 `cover` 配置)。[#54379](https://github.com/ant-design/ant-design/pull/54379) [@765477020](https://github.com/765477020)
- 🐞 修复 Image 在 RTL 下预览文案的展示问题。[#53596](https://github.com/ant-design/ant-design/pull/53596) [@aojunhao123](https://github.com/aojunhao123)
- Modal
- 🆕 Modal `closable` 支持 `onClose` 属性以任意方式关闭时触发。[#54607](https://github.com/ant-design/ant-design/pull/54607) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 ConfigProvider 支持配置 Modal 的 `okButtonProps` 和 `cancelButtonProps`。[#53684](https://github.com/ant-design/ant-design/pull/53684) [@guoyunhe](https://github.com/guoyunhe)
- 🛠 Modal 调整 DOM `className` 以与语义化结构规范保持一致。[#54472](https://github.com/ant-design/ant-design/pull/54472) [@thinkasany](https://github.com/thinkasany)
- ⌨️ 将 Modal 在 `closable` 对象中配置的 `aria-*` 属性应用到关闭按钮上。[#53289](https://github.com/ant-design/ant-design/pull/53289) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Modal 快速切换 `open` 状态时,屏幕交互会被锁定的问题。[#52753](https://github.com/ant-design/ant-design/pull/52753) [@zombieJ](https://github.com/zombieJ)
- Tabs
- 🆕 Tabs `tabPosition` 替换为 `tabPlacement`,并使用位置描述值 `start` 和 `end` 取代 `left` 和 `right`。[#54358](https://github.com/ant-design/ant-design/pull/54358) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 Tabs 移除激活态文字阴影。[#53617](https://github.com/ant-design/ant-design/pull/53617) [@guoyunhe](https://github.com/guoyunhe)
- 🐞 Tabs 修复空内容 TabPane 的焦点行为,提升无障碍体验。[#52856](https://github.com/ant-design/ant-design/pull/52856) [@aojunhao123](https://github.com/aojunhao123)
- 🛠 移除 Tabs 废弃 API。[#52768](https://github.com/ant-design/ant-design/pull/52768) [@aojunhao123](https://github.com/aojunhao123)
- Theme
- 🔥 支持通过 ConfigProvider 的 `theme` 中开启 `zeroRuntime`,屏蔽 cssinjs 样式生成。[#54334](https://github.com/ant-design/ant-design/pull/54334) [@MadCcc](https://github.com/MadCcc)
- 🆕 杂项:CSS-in-JS 支持配置 `autoPrefixTransformer` 添加浏览器样式前缀。[#54427](https://github.com/ant-design/ant-design/pull/54427) [@zombieJ](https://github.com/zombieJ)
- 🆕 Design Token: 在 `useToken` 中透出 css 变量。[#53195](https://github.com/ant-design/ant-design/pull/53195) [@MadCcc](https://github.com/MadCcc)
- 💄 杂项:从 reset.css 中移除 mark 样式。[#52974](https://github.com/ant-design/ant-design/pull/52974) [@afc163](https://github.com/afc163)
- 🔥 杂项:默认使用 CSS 变量。[#52671](https://github.com/ant-design/ant-design/pull/52671) [@MadCcc](https://github.com/MadCcc)
- 💄 Design Token 新增 `colorBorderDisabled` token 以统一禁用状态下的边框颜色。[#52421](https://github.com/ant-design/ant-design/pull/52421) [@aojunhao123](https://github.com/aojunhao123)
- Segmented
- 🆕 Segmented 支持 `items.tooltip` 属性以配置提示信息。[#54273](https://github.com/ant-design/ant-design/pull/54273) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Segmented 增加 `orientation` 属性用于布局,原 `vertical` 语法糖仍然保留。[#53664](https://github.com/ant-design/ant-design/pull/53664) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 改善 Segmented 组件可访问性。[#52618](https://github.com/ant-design/ant-design/pull/52618) [@aojunhao123](https://github.com/aojunhao123)
- 🛠 重命名 Steps 的 `labelPlacement` 为 `titlePlacement` 以统一 API。[#53873](https://github.com/ant-design/ant-design/pull/53873) [@zombieJ](https://github.com/zombieJ)
- Space
- 🛠 Space 使用 `separator` 代替 `split`。[#53983](https://github.com/ant-design/ant-design/pull/53983) [@thinkasany](https://github.com/thinkasany)
- 🛠 Space 使用 `orientation` 代替 `direction` 属性。[#53669](https://github.com/ant-design/ant-design/pull/53669) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Spin 支持 `styles.wrapper`。[#53448](https://github.com/ant-design/ant-design/pull/53448) [@crazyair](https://github.com/crazyair)
- Splitter
- 🆕 Splitter 使用 `orientation` 代替 `layout`,并增加 `vertical` 属性。[#53670](https://github.com/ant-design/ant-design/pull/53670) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Splitter 新增自定义拖拽图标。[#52216](https://github.com/ant-design/ant-design/pull/52216) [@wanpan11](https://github.com/wanpan11)
- Tour
- 🐞 修复 Tour 在滚动时,弹层不跟随的问题。[#53140](https://github.com/ant-design/ant-design/pull/53140) [@dependabot](https://github.com/dependabot)
- 🐞 修复 Tour dom 结构中 `panel` 的 `className` 拼写错误。[#55178](https://github.com/ant-design/ant-design/pull/55178) [@thinkasany](https://github.com/thinkasany)
- Button
- 🆕 Button `iconPosition` 替换为 `iconPlacement` 并支持逻辑位置描述。[#54279](https://github.com/ant-design/ant-design/pull/54279) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 Button `variant` 与 `color` 样式重构为 css variables 版本以降低尺寸。[#54100](https://github.com/ant-design/ant-design/pull/54100) [@zombieJ](https://github.com/zombieJ)
- 🆕 Button 新增自定义普通、虚线类型的按钮在禁用状态下的背景颜色。[#52839](https://github.com/ant-design/ant-design/pull/52839) [@yellowryan](https://github.com/yellowryan)
- Tag
- 🆕 Tag 新增 CheckableTagGroup 子组件。[#53256](https://github.com/ant-design/ant-design/pull/53256) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Tag 自定义颜色支持变体。[#53097](https://github.com/ant-design/ant-design/pull/53097) [@guoyunhe](https://github.com/guoyunhe)
- 🆕 Tag 新增 `disabled` 和 `href` 属性。[#52229](https://github.com/ant-design/ant-design/pull/52229) [@aojunhao123](https://github.com/aojunhao123)
- 🐞 修复 Tag 通过 ConfigProvider 修改 `variant` 时,Tag 不会更新的问题。[#55555](https://github.com/ant-design/ant-design/pull/55555) [@thinkasany](https://github.com/thinkasany)
- 💄 移除 Tag `margin` 样式。[#52123](https://github.com/ant-design/ant-design/pull/52123) [@li-jia-nan](https://github.com/li-jia-nan)
- Timeline
- 🆕 Timeline 支持 `titleSpan` 以配置 `title` 占用尺寸。[#54072](https://github.com/ant-design/ant-design/pull/54072) [@zombieJ](https://github.com/zombieJ)
- 🆕 Timeline 支持 `orientation=horizontal` 布局。[#54031](https://github.com/ant-design/ant-design/pull/54031) [@zombieJ](https://github.com/zombieJ)
- 🆕 TimeLine `items.position` 替换为 `items.placement` 并使用逻辑位置以优化 RTL 体验。[#54382](https://github.com/ant-design/ant-design/pull/54382) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Transfer 新增 `actions` 属性可用于自定义操作按钮。[#54104](https://github.com/ant-design/ant-design/pull/54104) [@afc163](https://github.com/afc163)
- 🆕 Carousel `dotPosition` 替换为 `dotPlacement`,使用位置描述值 `start` 和 `end` 取代 `left` 和 `right`。[#54294](https://github.com/ant-design/ant-design/pull/54294) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Divider 使用 `orientation` 替换 `type`,并且支持 `vertical` 语法糖。[#53645](https://github.com/ant-design/ant-design/pull/53645) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🛠 AutoComplete 将搜索相关属性合并至 `showSearch` 属性。[#54184](https://github.com/ant-design/ant-design/pull/54184) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🆕 Menu 支持 `popupRender` 属性自定义弹出层。[#53566](https://github.com/ant-design/ant-design/pull/53566) [@Zyf665](https://github.com/Zyf665)
- 🆕 Message 支持 `pauseOnHover` 以配置用户在悬浮时暂停倒计时。[#53785](https://github.com/ant-design/ant-design/pull/53785) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 `reset.css` 移除对 IE 的兼容。[#55108](https://github.com/ant-design/ant-design/pull/55108) [@thinkasany](https://github.com/thinkasany)
- 🛠 Slider 支持 `orientation` 用于配置布局方向。[#53671](https://github.com/ant-design/ant-design/pull/53671) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 移除 InputNumber 移动端对于控制器默认隐藏。[#54900](https://github.com/ant-design/ant-design/pull/54900) [@Wxh16144](https://github.com/Wxh16144)
- 💄 Image 遮罩添加模糊效果。[#54714](https://github.com/ant-design/ant-design/pull/54714) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 💄 Modal 遮罩添加模糊效果。[#54670](https://github.com/ant-design/ant-design/pull/54670) [@EmilyyyLiu](https://github.com/EmilyyyLiu)
- 🐞 修复 Statistic.Timer 在页面进入非激活态时,`onFinish` 和 `onChange` 未触发的问题。[#53894](https://github.com/ant-design/ant-design/pull/53894) [@Psiphonc](https://github.com/Psiphonc)
- 🛠 废弃 List 组件并且从官网移除。[#54182](https://github.com/ant-design/ant-design/pull/54182) [@zombieJ](https://github.com/zombieJ)
- 🛠 BackTop 完成生命周期已被移除。[#52206](https://github.com/ant-design/ant-design/pull/52206) [@li-jia-nan](https://github.com/li-jia-nan)
- 🗑 Icon 占位组件完成生命周期已被移除。[#52241](https://github.com/ant-design/ant-design/pull/52241) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 移除 Dropdown.Button,请使用 Space.Compact。[#53793](https://github.com/ant-design/ant-design/pull/53793) [@Meet-student](https://github.com/Meet-student)
- 🛠 Badge 重构 `offset` 样式偏移为 CSS 逻辑位置。[#55245](https://github.com/ant-design/ant-design/pull/55245) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 杂项:替换 `classNames` 库为 `clsx`。[0246702](https://github.com/ant-design/ant-design/commit/0246702) [#55164](https://github.com/ant-design/ant-design/pull/55164) [@lijianan](https://github.com/lijianan)
- 🛠 杂项:移除 MediaQueryList 针对旧版浏览器的兼容代码。[#55396](https://github.com/ant-design/ant-design/pull/55396) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 杂项:移除 React 19 兼容代码,现在 antd 默认支持 React 19。[#55274](https://github.com/ant-design/ant-design/pull/55274) [@li-jia-nan](https://github.com/li-jia-nan)
- 🛠 杂项:移除 `copy-to-clipboard` 依赖。[#54448](https://github.com/ant-design/ant-design/pull/54448) [@765477020](https://github.com/765477020)
- 🔥 杂项:提升构建目标版本,不再支持 IE。[#53390](https://github.com/ant-design/ant-design/pull/53390) [@zombieJ](https://github.com/zombieJ)
- 🔥 杂项:在打包产物 `antd.js` 以及 `antd.min.js` 中启用了 `React Compiler` 以优化性能,对使用 CJS/ESM 场景的用户可自行选择开启,参考[React 官方文档](https://zh-hans.react.dev/learn/react-compiler)。 [#55781](https://github.com/ant-design/ant-design/pull/55781) [@li-jia-nan](https://github.com/li-jia-nan)
- 🔥 杂项:颜色相关组件现在支持预设颜色名(如 `red`, `blue`, `green` 等等)。[#53241](https://github.com/ant-design/ant-design/pull/53241) [@zombieJ](https://github.com/zombieJ)
- 🌐 添加马拉地语国际化翻译。[#55179](https://github.com/ant-design/ant-design/pull/55179) [@divyeshagrawal](https://github.com/divyeshagrawal)
- TypeScript
- 🤖 优化 Notification `duration` 定义,现在禁止关闭为 `false`。[#55580](https://github.com/ant-design/ant-design/pull/55580) [@wanpan11](https://github.com/wanpan11)
## 5.x
去 [GitHub](https://github.com/ant-design/ant-design/blob/5.x-stable/CHANGELOG.zh-CN.md) 查看 `5.x` 的 Change Log。
## 4.x
去 [GitHub](https://github.com/ant-design/ant-design/blob/4.x-stable/CHANGELOG.zh-CN.md) 查看 `4.x` 的 Change Log。
## 3.x
去 [GitHub](https://github.com/ant-design/ant-design/blob/3.x-stable/CHANGELOG.zh-CN.md) 查看 `3.x` 的 Change Log。
## 2.x
去 [GitHub](https://github.com/ant-design/ant-design/blob/2.x-stable/CHANGELOG.zh-CN.md) 查看 `2.x` 的 Change Log。
## 1.11.4
去 [GitHub](https://github.com/ant-design/ant-design/blob/1.x-stable/CHANGELOG.md) 查看 `0.x` 到 `1.x` 的 Change Log。
---
## checkbox-cn
Source: https://ant.design/components/checkbox-cn.md
---
category: Components
group: 数据录入
title: Checkbox
subtitle: 多选框
description: 收集用户的多项选择。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*DzgiRbW3khIAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*G3MjTYXL6AIAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 在一组可选项中进行多项选择时;
- 单独使用可以表示两种状态之间的切换,和 `switch` 类似。区别在于切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。
## 代码演示 {#examples}
### 基本用法
简单的 checkbox。
```tsx
import React from 'react';
import { Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
const onChange: CheckboxProps['onChange'] = (e) => {
console.log(`checked = ${e.target.checked}`);
};
const App: React.FC = () => Checkbox ;
export default App;
```
### 不可用
checkbox 不可用。
```tsx
import React from 'react';
import { Checkbox, Flex } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 受控的 Checkbox
联动 checkbox。
```tsx
import React, { useState } from 'react';
import { Button, Checkbox } from 'antd';
import type { CheckboxProps } from 'antd';
const App: React.FC = () => {
const [checked, setChecked] = useState(true);
const [disabled, setDisabled] = useState(false);
const toggleChecked = () => {
setChecked(!checked);
};
const toggleDisable = () => {
setDisabled(!disabled);
};
const onChange: CheckboxProps['onChange'] = (e) => {
console.log('checked = ', e.target.checked);
setChecked(e.target.checked);
};
const label = `${checked ? 'Checked' : 'Unchecked'}-${disabled ? 'Disabled' : 'Enabled'}`;
return (
<>
{label}
{!checked ? 'Check' : 'Uncheck'}
{!disabled ? 'Disable' : 'Enable'}
>
);
};
export default App;
```
### Checkbox 组
方便的从数组生成 Checkbox 组。
```tsx
import React from 'react';
import { Checkbox } from 'antd';
import type { CheckboxOptionType, GetProp } from 'antd';
const onChange: GetProp = (checkedValues) => {
console.log('checked = ', checkedValues);
};
const plainOptions = ['Apple', 'Pear', 'Orange'];
const options: CheckboxOptionType[] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3' },
];
const optionsWithDisabled: CheckboxOptionType[] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3', disabled: false },
];
const App: React.FC = () => (
<>
>
);
export default App;
```
### 全选
在实现全选效果时,你可能会用到 `indeterminate` 属性。
```tsx
import React, { useState } from 'react';
import { Checkbox, Divider } from 'antd';
import type { CheckboxProps } from 'antd';
const CheckboxGroup = Checkbox.Group;
const plainOptions = ['Apple', 'Pear', 'Orange'];
const defaultCheckedList = ['Apple', 'Orange'];
const App: React.FC = () => {
const [checkedList, setCheckedList] = useState(defaultCheckedList);
const checkAll = plainOptions.length === checkedList.length;
const indeterminate = checkedList.length > 0 && checkedList.length < plainOptions.length;
const onChange = (list: string[]) => {
setCheckedList(list);
};
const onCheckAllChange: CheckboxProps['onChange'] = (e) => {
setCheckedList(e.target.checked ? plainOptions : []);
};
return (
<>
Check all
>
);
};
export default App;
```
### 布局
Checkbox.Group 内嵌 Checkbox 并与 Grid 组件一起使用,可以实现灵活的布局。
```tsx
import React from 'react';
import { Checkbox, Col, Row } from 'antd';
import type { GetProp } from 'antd';
const onChange: GetProp = (checkedValues) => {
console.log('checked = ', checkedValues);
};
const App: React.FC = () => (
A
B
C
D
E
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Checkbox 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Checkbox, Flex } from 'antd';
import type { CheckboxProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import { clsx } from 'clsx';
const useStyles = createStyles(({ token, css }) => ({
root: css`
border-radius: ${token.borderRadius}px;
background-color: ${token.colorBgContainer};
`,
icon: css`
border-color: ${token.colorWarning};
`,
label: css`
color: ${token.colorTextDisabled};
font-weight: bold;
`,
iconChecked: css`
background-color: ${token.colorWarning};
`,
labelChecked: css`
color: ${token.colorWarning};
`,
}));
// Object style
const styles: CheckboxProps['styles'] = {
icon: {
borderRadius: 6,
},
label: {
color: 'blue',
},
};
const App: React.FC = () => {
const { styles: classNamesStyles } = useStyles();
// Function classNames - dynamically adjust based on checked state
const classNamesFn: CheckboxProps['classNames'] = (
info,
): GetProp => {
if (info.props.checked) {
return {
root: clsx(classNamesStyles.root),
icon: clsx(classNamesStyles.icon, classNamesStyles.iconChecked),
label: clsx(classNamesStyles.label, classNamesStyles.labelChecked),
};
}
return {
root: classNamesStyles.root,
icon: classNamesStyles.icon,
label: classNamesStyles.label,
};
};
return (
Object styles
Function styles
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
#### Checkbox
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| checked | 指定当前是否选中 | boolean | false | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| defaultChecked | 初始是否选中 | boolean | false | | × |
| disabled | 失效状态 | boolean | false | | × |
| indeterminate | 设置 indeterminate 状态,只负责样式控制 | boolean | false | | × |
| onChange | 变化时的回调函数 | (e: CheckboxChangeEvent) => void | - | | × |
| onBlur | 失去焦点时的回调 | function() | - | | × |
| onFocus | 获得焦点时的回调 | function() | - | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
#### Checkbox.Group
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| defaultValue | 默认选中的选项 | (string \| number)\[] | \[] | |
| disabled | 整组失效 | boolean | false | |
| name | CheckboxGroup 下所有 `input[type="checkbox"]` 的 `name` 属性 | string | - | |
| options | 指定可选项 | string\[] \| number\[] \| Option\[] | \[] | |
| value | 指定选中的选项 | (string \| number \| boolean)\[] | \[] | |
| title | 选项的 title | `string` | - | |
| className | 选项的类名 | `string` | - | 5.25.0 |
| style | 选项的样式 | `React.CSSProperties` | - | |
| onChange | 变化时的回调函数 | (checkedValue: T[]) => void | - | |
##### Option
```typescript
interface Option {
label: string;
value: string;
disabled?: boolean;
}
```
### 方法 {#methods}
#### Checkbox
| 名称 | 描述 | 版本 |
| ------------- | ------------------------- | ------ |
| blur() | 移除焦点 | |
| focus() | 获取焦点 | |
| nativeElement | 返回 Checkbox 的 DOM 节点 | 5.17.3 |
## Semantic DOM
https://ant.design/components/checkbox-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorWhite | 不随主题变化的纯白色 | string | |
| controlInteractiveSize | 控制组件的交互大小。 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationFast | 动效播放速度,快速。用于小型元素动画交互 | string | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInBack | 预设动效曲率 | string | |
| motionEaseOutBack | 预设动效曲率 | string | |
| paddingXS | 控制元素的特小内间距。 | number | |
## FAQ
### 为什么在 Form.Item 下不能绑定数据? {#faq-form-item-limitations}
Form.Item 默认绑定值属性到 `value` 上,而 Checkbox 的值属性为 `checked`。你可以通过 `valuePropName` 来修改绑定的值属性。
```tsx | pure
```
---
## collapse-cn
Source: https://ant.design/components/collapse-cn.md
---
category: Components
group: 数据展示
title: Collapse
subtitle: 折叠面板
description: 可以折叠/展开的内容区域。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*B7HKR5OBe8gAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*sir-TK0HkWcAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 对复杂区域进行分组和隐藏,保持页面的整洁。
- `手风琴` 是一种特殊的折叠面板,只允许单个内容区域展开。
## 代码演示 {#examples}
### 折叠面板
可以同时展开多个面板,这个例子默认展开了第一个。
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => {
const onChange = (key: string | string[]) => {
console.log(key);
};
return ;
};
export default App;
```
### 面板尺寸
折叠面板有大、中、小三种尺寸。
通过设置 `size` 为 `large` `small` 分别把折叠面板设为大、小尺寸。若不设置 `size`,则尺寸默认为中。
```tsx
import React from 'react';
import { Collapse, Divider } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const App: React.FC = () => (
<>
Medium Size
{text} }]}
/>
Small Size
{text} }]}
/>
Large Size
{text} }]}
/>
>
);
export default App;
```
### 手风琴
手风琴模式,始终只有一个面板处在激活状态。
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => ;
export default App;
```
### 面板嵌套
嵌套折叠面板。
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const itemsNest: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel nest panel',
children: {text}
,
},
];
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: ,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => {
const onChange = (key: string | string[]) => {
console.log(key);
};
return ;
};
export default App;
```
### 简洁风格
一套没有边框的简洁样式。
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = (
A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found
as a welcome guest in many households across the world.
);
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: text,
},
{
key: '2',
label: 'This is panel header 2',
children: text,
},
{
key: '3',
label: 'This is panel header 3',
children: text,
},
];
const App: React.FC = () => ;
export default App;
```
### 自定义面板
自定义各个面板的背景色、圆角、边距和图标。
```tsx
import type { CSSProperties } from 'react';
import React from 'react';
import { CaretRightOutlined } from '@ant-design/icons';
import type { CollapseProps } from 'antd';
import { Collapse, theme } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const getItems: (panelStyle: CSSProperties) => CollapseProps['items'] = (panelStyle) => [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
style: panelStyle,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
style: panelStyle,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
style: panelStyle,
},
];
const App: React.FC = () => {
const { token } = theme.useToken();
const panelStyle: React.CSSProperties = {
marginBottom: 24,
background: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
border: 'none',
};
return (
}
style={{ background: token.colorBgContainer }}
items={getItems(panelStyle)}
/>
);
};
export default App;
```
### 面板图标
在面板标题中加入图标。第三方图标库(如 lucide、react-icons)渲染出的裸 `` 也会与标题文字垂直居中对齐。
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
// Icons from third-party libraries (e.g. lucide, react-icons) render as a bare ``
// rather than an `.anticon` wrapper. It stays vertically centred with the title text.
const ChartIcon: React.FC = () => (
);
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: (
<>
Panel with an Ant Design icon
>
),
children: {text}
,
},
{
key: '2',
label: (
<>
Panel with a third-party icon
>
),
children: {text}
,
},
];
const App: React.FC = () => ;
export default App;
```
### 隐藏箭头
你可以通过 `showArrow={false}` 隐藏 `CollapsePanel` 组件的箭头图标。
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header with arrow icon',
children: {text}
,
},
{
key: '2',
label: 'This is panel header with no arrow icon',
children: {text}
,
showArrow: false,
},
];
const App: React.FC = () => {
const onChange = (key: string | string[]) => {
console.log(key);
};
return ;
};
export default App;
```
### 额外节点
自定义渲染每个面板右上角的内容。
```tsx
import React, { useState } from 'react';
import { SettingOutlined } from '@ant-design/icons';
import type { CollapseProps } from 'antd';
import { Collapse, Select } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const App: React.FC = () => {
const [expandIconPlacement, setExpandIconPlacement] =
useState('start');
const onPlacementChange = (newExpandIconPlacement: CollapseProps['expandIconPlacement']) => {
setExpandIconPlacement(newExpandIconPlacement);
};
const onChange = (key: string | string[]) => {
console.log(key);
};
const genExtra = () => (
{
// If you don't want click extra trigger collapse, you can prevent this:
event.stopPropagation();
}}
/>
);
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
extra: genExtra(),
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
extra: genExtra(),
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
extra: genExtra(),
},
];
return (
<>
Expand Icon Placement:
>
);
};
export default App;
```
### 幽灵折叠面板
将折叠面板的背景变成透明。
```tsx
import React from 'react';
import type { CollapseProps } from 'antd';
import { Collapse } from 'antd';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: {text}
,
},
{
key: '2',
label: 'This is panel header 2',
children: {text}
,
},
{
key: '3',
label: 'This is panel header 3',
children: {text}
,
},
];
const App: React.FC = () => ;
export default App;
```
### 可折叠触发区域
通过 `collapsible` 属性,可以设置面板的可折叠触发区域。
```tsx
import React from 'react';
import { Collapse, Space } from 'antd';
import { createStyles } from 'antd-style';
const text = `
A dog is a type of domesticated animal.
Known for its loyalty and faithfulness,
it can be found as a welcome guest in many households across the world.
`;
const useStyles = createStyles((props) => {
const { css } = props;
return {
content: css`
width: 100%;
`,
};
});
const App: React.FC = () => {
const { styles } = useStyles();
return (
{text},
},
]}
/>
{text},
},
]}
/>
{text},
},
]}
/>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Collapse 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import type { CollapseProps, GetProp } from 'antd';
import { Collapse, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
background-color: #fafafa;
border: 1px solid #e0e0e0;
border-radius: 8px;
`,
}));
const element = (
A dog is a type of domesticated animal. Known for its loyalty and faithfulness, it can be found
as a welcome guest in many households across the world.
);
const items: CollapseProps['items'] = [
{
key: '1',
label: 'This is panel header 1',
children: element,
},
{
key: '2',
label: 'This is panel header 2',
children: element,
},
{
key: '3',
label: 'This is panel header 3',
children: element,
},
];
const styles: CollapseProps['styles'] = {
root: {
backgroundColor: '#fafafa',
border: '1px solid #e0e0e0',
borderRadius: 8,
},
header: {
backgroundColor: '#f0f0f0',
padding: '12px 16px',
color: '#141414',
},
};
const stylesFn: CollapseProps['styles'] = ({
props,
}): GetProp => {
if (props.size === 'large') {
return {
root: {
backgroundColor: '#fff',
border: '1px solid #696FC7',
borderRadius: 8,
},
header: {
backgroundColor: '#F5EFFF',
padding: '12px 16px',
color: '#141414',
},
};
}
};
const App: React.FC = () => {
const sharedProps: CollapseProps = { classNames, items };
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Collapse
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| accordion | 手风琴模式 | boolean | false | | × |
| activeKey | 当前激活 tab 面板的 key | string\[] \| string number\[] \| number | [手风琴模式](#collapse-demo-accordion)下默认第一个元素 | | × |
| bordered | 带边框风格的折叠面板 | boolean | true | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| collapsible | 所有子面板是否可折叠或指定可折叠触发区域 | `header` \| `icon` \| `disabled` | - | 4.9.0 | × |
| defaultActiveKey | 初始化选中面板的 key | string\[] \| string number\[] \| number | - | | × |
| ~~destroyInactivePanel~~ | 销毁折叠隐藏的面板 | boolean | false | | × |
| destroyOnHidden | 销毁折叠隐藏的面板 | boolean | false | 5.25.0 | × |
| expandIcon | 自定义切换图标 | (panelProps) => ReactNode | - | | 5.15.0 |
| expandIconPlacement | 设置图标位置 | `start` \| `end` | `start` | - | × |
| ~~expandIconPosition~~ | 设置图标位置,请使用 `expandIconPlacement` 替换 | `start` \| `end` | - | 4.21.0 | × |
| ghost | 使折叠面板透明且无边框 | boolean | false | 4.4.0 | × |
| size | 设置折叠面板大小 | `large` \| `medium` \| `small` | `medium` | 5.2.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| onChange | 切换面板的回调 | function | - | | × |
| items | 折叠项目内容 | [ItemType](#itemtype) | - | 5.6.0 | × |
### ItemType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 语义化结构 className | [`Record`](#semantic-dom) | - | 5.21.0 |
| collapsible | 是否可折叠或指定可折叠触发区域 | `header` \| `icon` \| `disabled` | - | |
| children | body 区域内容 | ReactNode | - | |
| extra | 自定义渲染每个面板右上角的内容 | ReactNode | - | |
| forceRender | 被隐藏时是否渲染 body 区域 DOM 结构 | boolean | false | |
| key | 对应 activeKey | string \| number | - | |
| label | 面板标题 | ReactNode | - | - |
| showArrow | 是否展示当前面板上的箭头(为 false 时,collapsible 不能设为 icon) | boolean | true | |
| styles | 语义化结构 style | [`Record`](#semantic-dom) | - | 5.21.0 |
### Collapse.Panel
:::warning{title=已废弃}
版本 >= 5.6.0 时请使用 items 方式配置面板。
:::
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| collapsible | 是否可折叠或指定可折叠触发区域 | `header` \| `icon` \| `disabled` | - | 4.9.0 (icon: 4.24.0) |
| extra | 自定义渲染每个面板右上角的内容 | ReactNode | - | |
| forceRender | 被隐藏时是否渲染 body 区域 DOM 结构 | boolean | false | |
| header | 面板标题 | ReactNode | - | |
| key | 对应 activeKey | string \| number | - | |
| showArrow | 是否展示当前面板上的箭头(为 false 时,collapsible 不能设为 icon) | boolean | true | |
## Semantic DOM
https://ant.design/components/collapse-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Collapse)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderlessContentBg | 简约风格折叠面板的内容背景 | string | transparent |
| borderlessContentPadding | 简约风格折叠面板的内容内边距 | Padding \| undefined | 4px 16px 16px |
| contentBg | 折叠面板内容背景 | string | #ffffff |
| contentPadding | 折叠面板内容内边距 | Padding \| undefined | 16px 16px |
| contentPaddingLG | 大号折叠面板内容内边距 | Padding \| undefined | 24 |
| contentPaddingSM | 小号折叠面板内容内边距 | Padding \| undefined | 12 |
| headerBg | 折叠面板头部背景 | string | rgba(0,0,0,0.02) |
| headerPadding | 折叠面板头部内边距 | Padding \| undefined | 12px 16px |
| headerPaddingLG | 大号折叠面板头部内边距 | Padding \| undefined | 16px 24px 16px 16px |
| headerPaddingSM | 小号折叠面板头部内边距 | Padding \| undefined | 8px 12px 8px 8px |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingSM | 控制元素的小内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## color-picker-cn
Source: https://ant.design/components/color-picker-cn.md
---
category: Components
title: ColorPicker
subtitle: 颜色选择器
description: 用于选择颜色。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*PpY4RYNM8UcAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*EHL-QYJofZsAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 数据录入
---
## 何时使用 {#when-to-use}
当用户需要自定义颜色选择的时候使用。
## 代码演示 {#examples}
### 基本使用
最简单的使用方法。
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
const Demo = () => ;
export default Demo;
```
### 触发器尺寸大小
触发器有大、中、小三种尺寸。
通过设置 `size` 为 `large` `small` 分别把触发器设为大、小尺寸。若不设置 `size`,则尺寸默认为中。
```tsx
import React from 'react';
import { ColorPicker, Space } from 'antd';
const Demo = () => (
);
export default Demo;
```
### 受控模式
通过 `value` 和 `onChange` 设置组件为受控模式,如果通过 `onChangeComplete` 受控则会锁定展示颜色。
```tsx
import React, { useState } from 'react';
import { ColorPicker, Space } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = GetProp;
const Demo: React.FC = () => {
const [color, setColor] = useState('#1677ff');
return (
);
};
export default Demo;
```
### 渐变色
通过 `mode` 设置颜色为单一颜色还是渐变色。
```tsx
import React from 'react';
import { ColorPicker, Space } from 'antd';
const DEFAULT_COLOR = [
{
color: 'rgb(16, 142, 233)',
percent: 0,
},
{
color: 'rgb(135, 208, 104)',
percent: 100,
},
];
const Demo = () => (
{
console.log(color.toCssString());
}}
/>
{
console.log(color.toCssString());
}}
/>
);
export default Demo;
```
### 渲染触发器文本
渲染触发器的默认文本, `showText` 为 `true` 时生效。自定义文本时,可以使用 `showText` 为函数的方式,返回自定义的文本。
```tsx
import React, { useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { ColorPicker, Space } from 'antd';
const Demo = () => {
const [open, setOpen] = useState(false);
return (
Custom Text ({color.toHexString()}) }
/>
(
)}
/>
);
};
export default Demo;
```
### 禁用
设置为禁用状态。
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
export default () => ;
```
### 禁用透明度
禁用颜色透明度。
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
const Demo = () => ;
export default Demo;
```
### 清除颜色
清除已选择的颜色。
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
export default () => {
const [color, setColor] = React.useState('#1677ff');
return (
{
setColor(c.toHexString());
}}
/>
);
};
```
### 自定义触发器
自定义颜色面板的触发器。
```tsx
import React, { useMemo, useState } from 'react';
import { Button, ColorPicker } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = Extract, string | { cleared: any }>;
const Demo: React.FC = () => {
const [color, setColor] = useState('#1677ff');
const bgColor = useMemo(
() => (typeof color === 'string' ? color : color!.toHexString()),
[color],
);
const btnStyle: React.CSSProperties = {
backgroundColor: bgColor,
};
return (
open
);
};
export default Demo;
```
### 自定义触发事件
自定义颜色面板的触发事件,提供 `click` 和 `hover` 两个选项。
```tsx
import React from 'react';
import { ColorPicker } from 'antd';
const Demo = () => ;
export default Demo;
```
### 颜色编码
编码格式,支持`HEX`、`HSB`、`RGB`。
```tsx
import React, { useState } from 'react';
import { ColorPicker, Space } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = Extract, string | { cleared: any }>;
type Format = GetProp;
const HexCase: React.FC = () => {
const [colorHex, setColorHex] = useState('#1677ff');
const [formatHex, setFormatHex] = useState('hex');
const hexString = React.useMemo(
() => (typeof colorHex === 'string' ? colorHex : colorHex?.toHexString()),
[colorHex],
);
return (
HEX: {hexString}
);
};
const HsbCase: React.FC = () => {
const [colorHsb, setColorHsb] = useState('hsb(215, 91%, 100%)');
const [formatHsb, setFormatHsb] = useState('hsb');
const hsbString = React.useMemo(
() => (typeof colorHsb === 'string' ? colorHsb : colorHsb?.toHsbString()),
[colorHsb],
);
return (
HSB: {hsbString}
);
};
const RgbCase: React.FC = () => {
const [colorRgb, setColorRgb] = useState('rgb(22, 119, 255)');
const [formatRgb, setFormatRgb] = useState('rgb');
const rgbString = React.useMemo(
() => (typeof colorRgb === 'string' ? colorRgb : colorRgb?.toRgbString()),
[colorRgb],
);
return (
RGB: {rgbString}
);
};
const Demo: React.FC = () => (
);
export default Demo;
```
### 预设颜色
设置颜色选择器的预设颜色。
```tsx
import React from 'react';
import { generate, green, presetPalettes, red } from '@ant-design/colors';
import { ColorPicker, theme } from 'antd';
import type { ColorPickerProps } from 'antd';
type Presets = Required['presets'][number];
function genPresets(presets = presetPalettes) {
return Object.entries(presets).map(([label, colors]) => ({ label, colors, key: label }));
}
const Demo: React.FC = () => {
const { token } = theme.useToken();
const presets = genPresets({ primary: generate(token.colorPrimary), red, green });
return ;
};
export default Demo;
```
### 自定义面板
通过 `panelRender` 自由控制面板的渲染。
```tsx
import React from 'react';
import { cyan, generate, green, presetPalettes, red } from '@ant-design/colors';
import { Col, ColorPicker, Divider, Row, Space, theme } from 'antd';
import type { ColorPickerProps } from 'antd';
type Presets = Required['presets'][number];
function genPresets(presets = presetPalettes) {
return Object.entries(presets).map(([label, colors]) => ({ label, colors, key: label }));
}
const HorizontalLayoutDemo = () => {
const { token } = theme.useToken();
const presets = genPresets({
primary: generate(token.colorPrimary),
red,
green,
cyan,
});
const customPanelRender: ColorPickerProps['panelRender'] = (
_,
{ components: { Picker, Presets } },
) => (
);
return (
);
};
const BasicDemo = () => (
(
)}
/>
);
export default () => (
Add title:
Horizontal layout:
);
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 ColorPicker 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { ColorPicker, Flex, Space } from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
borderRadius: token.borderRadius,
},
}));
const stylesObject: ColorPickerProps['styles'] = {
popup: {
root: {
border: '1px solid #fff',
},
},
};
const stylesFn: ColorPickerProps['styles'] = (
info,
): GetProp => {
if (info.props.size === 'large') {
return {
popup: {
root: {
border: '1px solid #722ed1',
},
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> 自 `antd@5.5.0` 版本开始提供该组件。
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| :-- | :-- | :-- | :-- | :-- | --- |
| allowClear | 允许清除选择的颜色 | boolean | false | | × |
| arrow | 配置弹出的箭头 | `boolean \| { pointAtCenter: boolean }` | true | | 6.3.0 |
| children | 颜色选择器的触发器 | React.ReactNode | - | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| defaultValue | 颜色默认的值 | [ColorType](#colortype) | - | | × |
| defaultFormat | 颜色格式默认的值 | `rgb` \| `hex` \| `hsb` | `hex` | 5.9.0 | × |
| disabled | 禁用颜色选择器 | boolean | - | | × |
| disabledAlpha | 禁用透明度 | boolean | - | 5.8.0 | × |
| disabledFormat | 禁用选择颜色格式 | boolean | - | 5.22.0 | × |
| ~~destroyTooltipOnHide~~ | 关闭后是否销毁弹窗 | `boolean` | false | 5.7.0 | × |
| destroyOnHidden | 关闭后是否销毁弹窗 | `boolean` | false | 5.25.0 | × |
| format | 颜色格式 | `rgb` \| `hex` \| `hsb` | - | | × |
| mode | 选择器模式,用于配置单色与渐变 | `'single' \| 'gradient' \| ('single' \| 'gradient')[]` | `single` | 5.20.0 | × |
| open | 是否显示弹出窗口 | boolean | - | | × |
| presets | 预设的颜色 | [PresetColorType](#presetcolortype) | - | | × |
| placement | 弹出窗口的位置 | 同 `Tooltips` 组件的 [placement](/components/tooltip-cn/#api) 参数设计 | `bottomLeft` | | × |
| panelRender | 自定义渲染面板 | `(panel: React.ReactNode, extra: { components: { Picker: FC; Presets: FC } }) => React.ReactNode` | - | 5.7.0 | × |
| showText | 显示颜色文本 | boolean \| `(color: Color) => React.ReactNode` | - | 5.7.0 | × |
| size | 设置触发器大小 | `large` \| `medium` \| `small` | `medium` | 5.7.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| trigger | 颜色选择器的触发模式 | `hover` \| `click` | `click` | | × |
| value | 颜色的值 | [ColorType](#colortype) | - | | × |
| onChange | 颜色变化的回调 | `(value: Color, css: string) => void` | - | | × |
| onChangeComplete | 颜色选择完成的回调,通过 `onChangeComplete` 对 `value` 受控时拖拽不会改变展示颜色 | `(value: Color) => void` | - | 5.7.0 | × |
| onFormatChange | 颜色格式变化的回调 | `(format: 'hex' \| 'rgb' \| 'hsb') => void` | - | | × |
| onOpenChange | 当 `open` 被改变时的回调 | `(open: boolean) => void` | - | | × |
| onClear | 清除的回调 | `() => void` | - | 5.6.0 | × |
#### ColorType
```typescript
type ColorType =
| string
| Color
| {
color: string;
percent: number;
}[];
```
#### PresetColorType
```typescript
type PresetColorType = {
label: React.ReactNode;
defaultOpen?: boolean;
key?: React.Key;
colors: ColorType[];
};
```
### Color
| 参数 | 说明 | 类型 | 版本 |
| :-- | :-- | :-- | :-- |
| toCssString | 转换成 CSS 支持的格式 | `() => string` | 5.20.0 |
| toHex | 转换成 `hex` 格式字符,返回格式如:`1677ff` | `() => string` | - |
| toHexString | 转换成 `hex` 格式颜色字符串,返回格式如:`#1677ff` | `() => string` | - |
| toHsb | 转换成 `hsb` 对象 | `() => ({ h: number, s: number, b: number, a: number })` | - |
| toHsbString | 转换成 `hsb` 格式颜色字符串,返回格式如:`hsb(215, 91%, 100%)` | `() => string` | - |
| toRgb | 转换成 `rgb` 对象 | `() => ({ r: number, g: number, b: number, a: number })` | - |
| toRgbString | 转换成 `rgb` 格式颜色字符串,返回格式如:`rgb(22, 119, 255)` | `() => string` | - |
## Semantic DOM
https://ant.design/components/color-picker-cn/semantic.md
## FAQ
### 关于颜色赋值的问题 {#faq-color-assignment}
颜色选择器的值同时支持字符串色值和选择器生成的 `Color` 对象,但由于不同格式的颜色字符串互相转换会有精度误差问题,所以受控场景推荐使用选择器生成的 `Color` 对象来进行赋值操作,这样可以避免精度问题,保证取值是精准的,选择器也可以按照预期工作。
---
## config-provider-cn
Source: https://ant.design/components/config-provider-cn.md
---
category: Components
subtitle: 全局化配置
group: 其他
title: ConfigProvider
description: 为组件提供统一的全局化配置。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*NVKORa7BCVwAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YC4ERpGAddoAAAAAAAAAAAAADrJ8AQ/original
---
## 使用 {#usage}
ConfigProvider 使用 React 的 [context](https://zh-hans.react.dev/learn/passing-data-deeply-with-context) 特性,只需在应用外围包裹一次即可全局生效。
```tsx
import React from 'react';
import { ConfigProvider } from 'antd';
// ...
const Demo: React.FC = () => (
);
export default Demo;
```
### 内容安全策略(CSP){#csp}
部分组件为了支持波纹效果,使用了动态样式。如果开启了 Content Security Policy (CSP),你可以通过 `csp` 属性来进行配置:
```tsx
My Button
```
## 代码演示 {#examples}
### 国际化
此处列出 Ant Design 中需要国际化支持的组件,你可以在演示里切换语言。
```tsx
import React, { useState } from 'react';
import { EllipsisOutlined } from '@ant-design/icons';
import type {
ConfigProviderProps,
RadioChangeEvent,
TableProps,
TourProps,
UploadFile,
} from 'antd';
import {
Button,
Calendar,
ConfigProvider,
DatePicker,
Divider,
Form,
Image,
Input,
InputNumber,
Modal,
Pagination,
Popconfirm,
QRCode,
Radio,
Select,
Space,
Table,
theme,
TimePicker,
Tour,
Transfer,
Upload,
} from 'antd';
import enUS from 'antd/locale/en_US';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
type Locale = ConfigProviderProps['locale'];
dayjs.locale('en');
const { RangePicker } = DatePicker;
const columns: TableProps['columns'] = [
{
title: 'Name',
dataIndex: 'name',
filters: [{ text: 'filter1', value: 'filter1' }],
},
{
title: 'Age',
dataIndex: 'age',
},
];
const Page: React.FC = () => {
const { token } = theme.useToken();
const [open, setOpen] = useState(false);
const [tourOpen, setTourOpen] = useState(false);
const tourRefs = React.useRef([]);
const showModal = () => {
setOpen(true);
};
const hideModal = () => {
setOpen(false);
};
const info = () => {
Modal.info({
title: 'some info',
content: 'some info',
});
};
const confirm = () => {
Modal.confirm({
title: 'some info',
content: 'some info',
});
};
const steps: TourProps['steps'] = [
{
title: 'Upload File',
description: 'Put your files here.',
target: () => tourRefs.current[0],
},
{
title: 'Save',
description: 'Save your changes.',
target: () => tourRefs.current[1],
},
{
title: 'Other Actions',
description: 'Click to see other actions.',
target: () => tourRefs.current[2],
},
];
const fileList: UploadFile[] = [
{
uid: '-1',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-2',
percent: 50,
name: 'image.png',
status: 'uploading',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-3',
name: 'image.png',
status: 'error',
},
];
return (
Show Modal
Show info
Show confirm
Click to confirm
Submit
Locale Modal
console.log('refresh')}
/>
Tour
setTourOpen(true)}>
Begin Tour
{
node && tourRefs.current.splice(0, 0, node);
}}
>
{' '}
Upload
{
node && tourRefs.current.splice(1, 0, node);
}}
type="primary"
>
Save
{
node && tourRefs.current.splice(2, 0, node);
}}
icon={ }
/>
setTourOpen(false)} />
);
};
const App: React.FC = () => {
const [locale, setLocale] = useState(enUS);
const changeLocale = (e: RadioChangeEvent) => {
const localeValue = e.target.value;
setLocale(localeValue);
if (!localeValue) {
dayjs.locale('en');
} else {
dayjs.locale('zh-cn');
}
};
return (
<>
Change locale of components:
English
中文
>
);
};
export default App;
```
### 方向
这里列出了支持 `rtl` 方向的组件,您可以在演示中切换方向。
```tsx
import React, { useState } from 'react';
import {
DownloadOutlined,
LeftOutlined,
MinusOutlined,
PlusOutlined,
RightOutlined,
SearchOutlined as SearchIcon,
SmileOutlined,
} from '@ant-design/icons';
import type { ConfigProviderProps, RadioChangeEvent } from 'antd';
import {
Badge,
Button,
Cascader,
Col,
ConfigProvider,
Divider,
Flex,
Input,
InputNumber,
Modal,
Pagination,
Radio,
Rate,
Row,
Select,
Space,
Steps,
Switch,
Tree,
TreeSelect,
} from 'antd';
import { createStyles } from 'antd-style';
type DirectionType = ConfigProviderProps['direction'];
const useStyles = createStyles((props) => {
const { css } = props;
return {
headerExample: css`
display: inline-block;
width: 42px;
height: 42px;
vertical-align: middle;
background-color: #eee;
border-radius: 4px;
`,
};
});
const { Search } = Input;
const treeData = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
disabled: true,
children: [
{ title: 'leaf', key: '0-0-0-0', disableCheckbox: true },
{ title: 'leaf', key: '0-0-0-1' },
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{ title: sss , key: '0-0-1-0' }],
},
],
},
];
const treeSelectData = [
{
title: 'parent 1',
value: '0-1',
children: [
{
title: 'parent 1-0',
value: '0-1-1',
children: [
{ title: 'my leaf', value: 'random' },
{ title: 'your leaf', value: 'random1' },
],
},
{
title: 'parent 1-1',
value: 'random2',
children: [{ title: sss , value: 'random3' }],
},
],
},
];
const cascaderOptions = [
{
value: 'tehran',
label: 'تهران',
children: [
{
value: 'tehran-c',
label: 'تهران',
children: [
{
value: 'saadat-abad',
label: 'سعادت آباد',
},
],
},
],
},
{
value: 'ardabil',
label: 'اردبیل',
children: [
{
value: 'ardabil-c',
label: 'اردبیل',
children: [
{
value: 'pirmadar',
label: 'پیرمادر',
},
],
},
],
},
{
value: 'gilan',
label: 'گیلان',
children: [
{
value: 'rasht',
label: 'رشت',
children: [
{
value: 'district-3',
label: 'منطقه ۳',
},
],
},
],
},
];
type Placement = 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight';
const Page: React.FC<{ placement: Placement }> = (props) => {
const { placement } = props;
const { styles } = useStyles();
const [currentStep, setCurrentStep] = useState(0);
const [modalOpen, setModalOpen] = useState(false);
const [badgeCount, setBadgeCount] = useState(5);
const [showBadge, setShowBadge] = useState(true);
const selectBefore = (
);
const selectAfter = (
);
// ==== Cascader ====
const cascaderFilter = (inputValue: string, path: { label: string }[]) =>
path.some((option) => option.label.toLowerCase().includes(inputValue.toLowerCase()));
const onCascaderChange = (value: any) => {
console.log(value);
};
// ==== End Cascader ====
// ==== Modal ====
const showModal = () => {
setModalOpen(true);
};
const handleOk = () => {
setModalOpen(false);
};
const handleCancel = () => {
setModalOpen(false);
};
// ==== End Modal ====
const onStepsChange = (newCurrentStep: number) => {
console.log('onChange:', newCurrentStep);
setCurrentStep(newCurrentStep);
};
// ==== Badge ====
const increaseBadge = () => {
setBadgeCount(badgeCount + 1);
};
const declineBadge = () => {
setBadgeCount((prev) => (prev - 1 < 0 ? 0 : prev - 1));
};
const onChangeBadge = (checked: boolean) => {
setShowBadge(checked);
};
// ==== End Badge ====
return (
Cascader example
}
options={cascaderOptions}
onChange={onCascaderChange}
placeholder="یک مورد انتخاب کنید"
placement={placement}
/>
With search:
}
options={cascaderOptions}
onChange={onCascaderChange}
placeholder="Select an item"
placement={placement}
showSearch={{ filter: cascaderFilter }}
/>
Switch example
Radio Group example
تهران
اصفهان
فارس
خوزستان
Button example
} />
} />
} />
}>
Download
}>
Download
}>
Backward
} iconPlacement="end">
Forward
Loading
Loading
Tree example
Input (Input Group) example
{selectBefore}
{selectAfter}
Select example
TreeSelect example
Modal example
Open Modal
نگاشتههای خود را اینجا قراردهید
نگاشتههای خود را اینجا قراردهید
نگاشتههای خود را اینجا قراردهید
Steps example
Rate example
* Note: Half star not implemented in RTL direction, it will be
supported after{' '}
rc-rate
{' '}
implement rtl support.
Badge example
} onClick={declineBadge} />
} onClick={increaseBadge} />
Pagination example
Grid System example
* Note: Every calculation in RTL grid system is from right side
(offset, push, etc.)
col-8
col-8
col-6 col-offset-6
col-6 col-offset-6
col-12 col-offset-6
col-18 col-push-6
col-6 col-pull-18
);
};
const App: React.FC = () => {
const [direction, setDirection] = useState('ltr');
const [placement, setPlacement] = useState('bottomLeft');
const changeDirection = (e: RadioChangeEvent) => {
const directionValue = e.target.value;
setDirection(directionValue);
setPlacement(directionValue === 'rtl' ? 'bottomRight' : 'bottomLeft');
};
return (
<>
Change direction of components:
LTR
RTL
>
);
};
export default App;
```
### 组件尺寸
修改默认组件尺寸。
```tsx
import React, { useState } from 'react';
import {
Button,
Card,
ConfigProvider,
DatePicker,
Divider,
Input,
Radio,
Select,
Space,
Table,
Tabs,
} from 'antd';
import type { ConfigProviderProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const App: React.FC = () => {
const [componentSize, setComponentSize] = useState('small');
return (
<>
{
setComponentSize(e.target.value);
}}
>
Small
Medium
Large
Button
>
);
};
export default App;
```
### 主题
通过 `theme` 修改主题。
```tsx
import React from 'react';
import {
Button,
ColorPicker,
ConfigProvider,
Divider,
Form,
Input,
InputNumber,
Space,
Switch,
} from 'antd';
import type { ColorPickerProps, GetProp } from 'antd';
type Color = Extract, { cleared: any }>;
type ThemeData = {
borderRadius: number;
colorPrimary: string;
Button?: {
colorPrimary: string;
algorithm?: boolean;
};
};
const defaultData: ThemeData = {
borderRadius: 6,
colorPrimary: '#1677ff',
Button: {
colorPrimary: '#00B96B',
},
};
export default () => {
const [form] = Form.useForm();
const [data, setData] = React.useState(defaultData);
return (
);
};
```
### 自定义波纹
波纹效果带来了灵动性,可以通过 `component` 判断来自哪个组件。你也可以使用 [`@ant-design/happy-work-theme`](https://github.com/ant-design/happy-work-theme) 提供的 HappyProvider 实现动态波纹效果。
```tsx
import React from 'react';
import { HappyProvider } from '@ant-design/happy-work-theme';
import { Button, ConfigProvider, Flex } from 'antd';
import type { ConfigProviderProps, GetProp } from 'antd';
type WaveConfig = GetProp;
// Prepare effect holder
const createHolder = (node: HTMLElement) => {
const { borderWidth } = getComputedStyle(node);
const borderWidthNum = Number.parseInt(borderWidth, 10);
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.inset = `-${borderWidthNum}px`;
div.style.borderRadius = 'inherit';
div.style.background = 'transparent';
div.style.zIndex = '999';
div.style.pointerEvents = 'none';
div.style.overflow = 'hidden';
node.appendChild(div);
return div;
};
const createDot = (holder: HTMLElement, color: string, left: number, top: number, size = 0) => {
const dot = document.createElement('div');
dot.style.position = 'absolute';
dot.style.insetInlineStart = `${left}px`;
dot.style.top = `${top}px`;
dot.style.width = `${size}px`;
dot.style.height = `${size}px`;
dot.style.borderRadius = '50%';
dot.style.background = color;
dot.style.transform = 'translate3d(-50%, -50%, 0)';
dot.style.transition = 'all 1s ease-out';
holder.appendChild(dot);
return dot;
};
// Inset Effect
const showInsetEffect: WaveConfig['showEffect'] = (node, { event, component }) => {
if (component !== 'Button') {
return;
}
const holder = createHolder(node);
const rect = holder.getBoundingClientRect();
const left = event.clientX - rect.left;
const top = event.clientY - rect.top;
const dot = createDot(holder, 'rgba(255, 255, 255, 0.65)', left, top);
// Motion
requestAnimationFrame(() => {
dot.ontransitionend = () => {
holder.remove();
};
dot.style.width = '200px';
dot.style.height = '200px';
dot.style.opacity = '0';
});
};
// Shake Effect
const showShakeEffect: WaveConfig['showEffect'] = (node, { component }) => {
if (component !== 'Button') {
return;
}
const seq = [0, -15, 15, -5, 5, 0];
const itv = 10;
let steps = 0;
const loop = () => {
cancelAnimationFrame((node as any).effectTimeout);
(node as any).effectTimeout = requestAnimationFrame(() => {
const currentStep = Math.floor(steps / itv);
const current = seq[currentStep];
const next = seq[currentStep + 1];
if (next === undefined || next === null) {
node.style.transform = '';
node.style.transition = '';
return;
}
// Trans from current to next by itv
const angle = current + ((next - current) / itv) * (steps % itv);
node.style.transform = `rotate(${angle}deg)`;
node.style.transition = 'none';
steps += 1;
loop();
});
};
loop();
};
// Component
const Wrapper: React.FC = ({ name, ...wave }) => (
{name}
);
const Demo: React.FC = () => (
Happy Work
);
export default Demo;
```
### 静态方法
使用 `holderRender` 给 `message` 、`modal` 、`notification` 静态方法设置 `Provider`
```tsx
import React, { useContext, useLayoutEffect } from 'react';
import { StyleProvider } from '@ant-design/cssinjs';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { App, Button, ConfigProvider, message, Modal, notification, Space } from 'antd';
const Demo: React.FC = () => {
const { locale, theme } = useContext(ConfigProvider.ConfigContext);
useLayoutEffect(() => {
ConfigProvider.config({
holderRender: (children) => (
{children}
),
});
}, [locale, theme]);
return (
{
message.info('This is a normal message');
}}
>
message
{
notification.open({
title: 'Notification Title',
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
});
}}
>
notification
{
Modal.confirm({
title: 'Do you want to delete these items?',
icon: ,
content: 'Some descriptions',
});
}}
>
Modal
);
};
export default Demo;
```
## API
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| componentDisabled | 设置 antd 组件禁用状态 | boolean | - | 4.21.0 |
| componentSize | 设置 antd 组件大小 | `small` \| `medium` \| `large` | - | |
| csp | 设置 [Content Security Policy](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CSP) 配置 | { nonce: string } | - | |
| direction | 设置文本展示方向。 [示例](#config-provider-demo-direction) | `ltr` \| `rtl` | `ltr` | |
| getPopupContainer | 弹出框(Select, Tooltip, Menu 等等)渲染父节点,默认渲染到 body 上。 | `(trigger?: HTMLElement) => HTMLElement \| ShadowRoot` | () => document.body | |
| getTargetContainer | 配置 Affix、Anchor 滚动监听容器。 | `() => HTMLElement \| Window \| ShadowRoot` | () => window | 4.2.0 |
| iconPrefixCls | 设置图标统一样式前缀 | string | `anticon` | 4.11.0 |
| locale | 语言包配置,语言包可到 [antd/locale](https://unpkg.com/antd/locale/) 目录下寻找 | object | - | |
| popupMatchSelectWidth | 下拉菜单和选择器同宽。默认将设置 `min-width`,当值小于选择框宽度时会被忽略。`false` 时会关闭虚拟滚动 | boolean \| number | - | 5.5.0 |
| popupOverflow | Select 类组件弹层展示逻辑,默认为可视区域滚动,可配置成滚动区域滚动 | 'viewport' \| 'scroll' | 'viewport' | 5.5.0 |
| prefixCls | 设置统一样式前缀 | string | `ant` | |
| renderEmpty | 自定义组件空状态。参考 [空状态](/components/empty-cn) | function(componentName: string): ReactNode | - | |
| theme | 设置主题,参考 [定制主题](/docs/react/customize-theme-cn) | [Theme](/docs/react/customize-theme-cn#theme) | - | 5.0.0 |
| variant | 设置全局输入组件形态变体 | `outlined` \| `filled` \| `borderless` | - | 5.19.0 |
| virtual | 设置 `false` 时关闭虚拟滚动 | boolean | - | 4.3.0 |
| warning | 设置警告等级,`strict` 为 `false` 时会将废弃相关信息聚合为单条信息 | { strict: boolean } | - | 5.10.0 |
| ~~autoInsertSpaceInButton~~ | Button 自动空格配置,请使用 `button={{ autoInsertSpace: boolean }}` 替代 | boolean | - | - |
| ~~dropdownMatchSelectWidth~~ | 下拉菜单和选择器是否同宽,请使用 `popupMatchSelectWidth` 替代 | boolean | - | - |
### ConfigProvider.config() {#config}
设置 `Modal`、`Message`、`Notification` 静态方法配置,只会对非 hooks 的静态方法调用生效。
```tsx
ConfigProvider.config({
// 5.13.0+
holderRender: (children) => (
{children}
),
});
```
### ConfigProvider.useConfig() 5.3.0+ {#useconfig}
获取父级 `Provider` 的值,如 `DisabledContextProvider`、`SizeContextProvider`。
```jsx
const {
componentDisabled, // 5.3.0+
componentSize, // 5.3.0+
} = ConfigProvider.useConfig();
```
| 返回值 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| componentDisabled | antd 组件禁用状态 | boolean | - | 5.3.0 |
| componentSize | antd 组件大小状态 | `small` \| `medium` \| `large` | - | 5.3.0 |
### 组件配置 {#component-config}
以下配置项用于设置对应组件的通用属性或全局效果配置,具体 API 见链接:
- `affix`:[Affix](/components/affix-cn#api)(自 6.0.0 起支持)
- `alert`:[Alert](/components/alert-cn#api)(自 5.7.0 起支持)
- `anchor`:[Anchor](/components/anchor-cn#api)(自 6.0.0 起支持)
- `app`:[App](/components/app-cn#api)(自 6.3.0 起支持)
- `avatar`:[Avatar](/components/avatar-cn#api)(自 5.7.0 起支持)
- `badge`:[Badge](/components/badge-cn#api)(自 5.7.0 起支持)
- `borderBeam`:[BorderBeam](/components/border-beam-cn#api)(自 6.4.0 起支持)
- `breadcrumb`:[Breadcrumb](/components/breadcrumb-cn#api)(自 5.7.0 起支持)
- `button`:[Button](/components/button-cn#api)(自 5.6.0 起支持)
- `calendar`:[Calendar](/components/calendar-cn#api)(自 6.0.0 起支持)
- `card`:[Card](/components/card-cn#api)(自 5.14.0 起支持)
- `cardMeta`:[Card.Meta](/components/card-cn#cardmeta)(自 6.0.0 起支持)
- `carousel`:[Carousel](/components/carousel-cn#api)(自 5.7.0 起支持)
- `cascader`:[Cascader](/components/cascader-cn#api)(自 5.13.0 起支持)
- `checkbox`:[Checkbox](/components/checkbox-cn#api)(自 6.0.0 起支持)
- `collapse`:[Collapse](/components/collapse-cn#api)(自 5.15.0 起支持)
- `colorPicker`:[ColorPicker](/components/color-picker-cn#api)(自 6.3.0 起支持)
- `datePicker`:[DatePicker](/components/date-picker-cn#api)(自 5.7.0 起支持)
- `rangePicker`:[RangePicker](/components/date-picker-cn#rangepicker)(自 5.11.0 起支持)
- `descriptions`:[Descriptions](/components/descriptions-cn#api)(自 5.23.0 起支持)
- `divider`:[Divider](/components/divider-cn#api)(自 5.10.0 起支持)
- `drawer`:[Drawer](/components/drawer-cn#api)(自 5.10.0 起支持)
- `dropdown`:[Dropdown](/components/dropdown-cn#api)(自 5.11.0 起支持)
- `empty`:[Empty](/components/empty-cn#api)(自 5.23.0 起支持)
- `flex`:[Flex](/components/flex-cn#api)(自 5.10.0 起支持)
- `floatButton`:[FloatButton](/components/float-button-cn#api)(自 6.0.0 起支持)
- `floatButtonGroup`:[FloatButton.Group](/components/float-button-cn#floatbuttongroup)(自 5.16.0 起支持)
- `form`:[Form](/components/form-cn#api)(自 4.8.0 起支持)
- `image`:[Image](/components/image-cn#api)(自 5.14.0 起支持)
- `input`:[Input](/components/input-cn#input)(自 4.2.0 起支持)
- `inputNumber`:[InputNumber](/components/input-number-cn#api)(自 5.19.0 起支持)
- `otp`:[Input.OTP](/components/input-cn#inputotp)(自 6.0.0 起支持)
- `inputPassword`:[Input.Password](/components/input-cn#inputpassword)(自 6.4.0 起支持)
- `inputSearch`:[Input.Search](/components/input-cn#inputsearch)(自 6.4.0 起支持)
- `textArea`:[Input.TextArea](/components/input-cn#inputtextarea)(自 5.15.0 起支持)
- `layout`:[Layout](/components/layout-cn#api)(自 5.7.0 起支持)
- `list`:[List](/components/list-cn#api)(自 5.7.0 起支持)
- `masonry`:[Masonry](/components/masonry-cn#api)(自 6.0.0 起支持)
- `menu`:[Menu](/components/menu-cn#api)(自 5.15.0 起支持)
- `mentions`:[Mentions](/components/mentions-cn#api)(自 5.13.0 起支持)
- `message`:[Message](/components/message-cn#api)(自 5.7.0 起支持)
- `modal`:[Modal](/components/modal-cn#api)(自 5.10.0 起支持)
- `notification`:[Notification](/components/notification-cn#api)(自 5.14.0 起支持)
- `pagination`:[Pagination](/components/pagination-cn#api)(自 6.0.0 起支持)
- `progress`:[Progress](/components/progress-cn#api)(自 5.7.0 起支持)
- `radio`:[Radio](/components/radio-cn#api)(自 6.0.0 起支持)
- `rate`:[Rate](/components/rate-cn#api)(自 5.7.0 起支持)
- `result`:[Result](/components/result-cn#api)(自 6.0.0 起支持)
- `ribbon`:[Badge.Ribbon](/components/badge-cn#badgeribbon)(自 6.0.0 起支持)
- `skeleton`:[Skeleton](/components/skeleton-cn#api)(自 6.0.0 起支持)
- `segmented`:[Segmented](/components/segmented-cn#api)(自 6.0.0 起支持)
- `select`:[Select](/components/select-cn#api)(自 5.13.0 起支持)
- `slider`:[Slider](/components/slider-cn#api)(自 5.23.0 起支持)
- `switch`:[Switch](/components/switch-cn#api)(自 6.0.0 起支持)
- `space`:[Space](/components/space-cn#api)(自 5.6.0 起支持)
- `splitter`:[Splitter](/components/splitter-cn#api)(自 5.21.0 起支持)
- `spin`:[Spin](/components/spin-cn#api)(自 5.20.0 起支持)
- `statistic`:[Statistic](/components/statistic-cn#api)(自 6.0.0 起支持)
- `steps`:[Steps](/components/steps-cn#api)(自 5.10.0 起支持)
- `table`:[Table](/components/table-cn#api)(自 6.2.0 起支持)
- `tabs`:[Tabs](/components/tabs-cn#api)(自 5.14.0 起支持)
- `tag`:[Tag](/components/tag-cn#api)(自 5.14.0 起支持)
- `timeline`:[Timeline](/components/timeline-cn#api)(自 6.0.0 起支持)
- `timePicker`:[TimePicker](/components/time-picker-cn#api)(自 5.13.0 起支持)
- `tour`:[Tour](/components/tour-cn#api)(自 5.14.0 起支持)
- `tooltip`:[Tooltip](/components/tooltip-cn#api)(自 6.1.0 起支持)
- `popover`:[Popover](/components/popover-cn#api)(自 5.23.0 起支持)
- `popconfirm`:[Popconfirm](/components/popconfirm-cn#api)(自 5.23.0 起支持)
- `qrcode`:[QRCode](/components/qr-code-cn#api)(自 6.0.0 起支持)
- `transfer`:[Transfer](/components/transfer-cn#api)(自 5.7.0 起支持)
- `tree`:[Tree](/components/tree-cn#api)(自 6.0.0 起支持)
- `treeSelect`:[TreeSelect](/components/tree-select-cn#api)(自 5.19.0 起支持)
- `typography`:[Typography](/components/typography-cn#api)(自 6.4.0 起支持)
- `upload`:[Upload](/components/upload-cn#api)(自 5.27.0 起支持)
- `watermark`:[Watermark](/components/watermark-cn#api)(自 6.0.0 起支持)
- `wave`:[WaveConfig](#waveconfig)(自 5.8.0 起支持)
### WaveConfig
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| disabled | 是否禁用水波纹效果 | boolean | false | |
| showEffect | 自定义水波纹效果 | (node: HTMLElement, info: { className, token, component }) => void | - | |
| triggerType | 触发水波纹效果的事件 | `click` \| `pointerdown` \| `pointerup` \| `mousedown` \| `mouseup` | `click` | 6.4.0 |
## FAQ
### 如何增加一个新的语言包? {#faq-add-locale}
参考[《增加语言包》](/docs/react/i18n#%E5%A2%9E%E5%8A%A0%E8%AF%AD%E8%A8%80%E5%8C%85)。
### 为什么时间类组件的国际化 locale 设置不生效? {#faq-locale-not-work}
参考 FAQ [为什么时间类组件的国际化 locale 设置不生效?](/docs/react/faq#为什么时间类组件的国际化-locale-设置不生效)。
### 配置 `getPopupContainer` 导致 Modal 报错? {#faq-get-popup-container}
相关 issue:
当如下全局设置 `getPopupContainer` 为触发节点的 parentNode 时,由于 Modal 的用法不存在 `triggerNode`,这样会导致 `triggerNode is undefined` 的报错,需要增加一个[判断条件](https://github.com/afc163/feedback-antd/commit/3e4d1ad1bc1a38460dc3bf3c56517f737fe7d44a)。
```diff
triggerNode.parentNode}
+ getPopupContainer={node => {
+ if (node) {
+ return node.parentNode;
+ }
+ return document.body;
+ }}
>
```
### 为什么 message.info、notification.open 或 Modal.confirm 等方法内的 ReactNode 无法继承 ConfigProvider 的属性?比如 `prefixCls` 和 `theme`。 {#faq-message-inherit}
静态方法是使用 ReactDOM.render 重新渲染一个 React 根节点上,和主应用的 React 节点是脱离的。我们建议使用 useMessage、useNotification 和 useModal 来使用相关方法。原先的静态方法在 5.0 中已被废弃。
### Vite 生产模式打包后国际化 locale 设置不生效? {#faq-vite-locale-not-work}
相关 issue:[#39045](https://github.com/ant-design/ant-design/issues/39045)
由于 Vite 生产模式下打包与开发模式不同,cjs 格式的文件会多一层,需要 `zhCN.default` 来获取。推荐 Vite 用户直接从 `antd/es/locale` 目录下引入 esm 格式的 locale 文件。
### prefixCls 优先级(前者被后者覆盖) {#faq-prefixcls-priority}
1. `ConfigProvider.config({ prefixCls: 'prefix-1' })`
2. `ConfigProvider.config({ holderRender: (children) => {children} })`
3. `message.config({ prefixCls: 'prefix-3' })`
---
## date-picker-cn
Source: https://ant.design/components/date-picker-cn.md
---
category: Components
group: 数据录入
title: DatePicker
subtitle: 日期选择框
description: 输入或选择日期的控件。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*qK9mRqFnBbAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*wz1QTJSQgmAAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。
## 代码演示 {#examples}
### 基本
最简单的用法,在浮层中可以选择或者输入日期。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Flex } from 'antd';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const Demo: React.FC = () => (
);
export default Demo;
```
### 范围选择器
通过设置 `picker` 属性,指定范围选择器类型。
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => (
{
console.log('Focus:', info.range);
}}
onBlur={(_, info) => {
console.log('Blur:', info.range);
}}
/>
);
export default App;
```
### 多选
多选,不支持 `showTime` 以及 `picker="time"`。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Flex } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const defaultValue = [dayjs('2000-01-01'), dayjs('2000-01-03'), dayjs('2000-01-05')];
const App: React.FC = () => (
);
export default App;
```
### 选择确认
DatePicker 默认会根据 `picker` 的交互行为,自动选择是否需要确认按钮。你也可以通过 `needConfirm` 属性来手动设置是否需要确认按钮。当有 `needConfirm` 时,用户始终需要点击确认按钮才能完成选择。反之,则会在选择或者失去焦点时提交。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker } from 'antd';
import type { Dayjs } from 'dayjs';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const App: React.FC = () => ;
export default App;
```
### 切换不同的选择器
提供选择器,自由切换不同类型的日期选择器,常用于日期筛选场合。
```tsx
import React, { useState } from 'react';
import type { DatePickerProps, TimePickerProps } from 'antd';
import { DatePicker, Select, Space, TimePicker } from 'antd';
import type { Dayjs } from 'dayjs';
type PickerType = 'time' | 'date';
interface PickerWithTypeProps {
type: PickerType;
onChange: TimePickerProps['onChange'] | DatePickerProps['onChange'];
}
const PickerWithType: React.FC = ({ type, onChange }) => {
if (type === 'time') {
return ;
}
if (type === 'date') {
return ;
}
return ;
};
const App: React.FC = () => {
const [type, setType] = useState('time');
return (
console.log(value)} />
);
};
export default App;
```
### 日期格式
使用 `format` 属性,可以自定义日期显示格式。当 `format` 为数组时,选择器输入框可以输入数组中任意一个有效格式。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const weekFormat = 'MM/DD';
const monthFormat = 'YYYY/MM';
/** Manually entering any of the following formats will perform date parsing */
const dateFormatList = ['DD/MM/YYYY', 'DD/MM/YY', 'DD-MM-YYYY', 'DD-MM-YY'];
const customFormat: DatePickerProps['format'] = (value) =>
`custom format: ${value.format(dateFormat)}`;
const customWeekStartEndFormat: DatePickerProps['format'] = (value) =>
`${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value)
.endOf('week')
.format(weekFormat)}`;
const App: React.FC = () => (
);
export default App;
```
### 日期时间选择
增加选择时间功能,当 `showTime` 为一个对象时,其属性会传递给内建的 `TimePicker`。
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
import type { DatePickerProps, GetProps } from 'antd';
type RangePickerProps = GetProps;
const { RangePicker } = DatePicker;
const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {
console.log('onOk: ', value);
};
const App: React.FC = () => (
{
console.log('Selected Time: ', value);
console.log('Formatted Selected Time: ', dateString);
}}
onOk={onOk}
/>
{
console.log('Selected Time: ', value);
console.log('Formatted Selected Time: ', dateString);
}}
onOk={onOk}
/>
);
export default App;
```
### 格式对齐
输入格式对齐,通过键盘左右切换焦点。失去焦点时会尝试对齐到最后合法的日期。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const App: React.FC = () => (
);
export default App;
```
### 日期限定范围
通过 `minDate` 和 `maxDate` 限定日期范围。
```tsx
import React from 'react';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';
const App: React.FC = () => (
);
export default App;
```
### 禁用
选择框的不可用状态。你也可以通过数组单独禁用 RangePicker 的其中一项。
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const App: React.FC = () => (
);
export default App;
```
### 不可选择日期和时间
可用 `disabledDate` 和 `disabledTime` 分别禁止选择部分日期和时间,其中 `disabledTime` 需要和 `showTime` 一起使用。
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
import type { GetProps } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
type RangePickerProps = GetProps;
dayjs.extend(customParseFormat);
const { RangePicker } = DatePicker;
const range = (start: number, end: number) => {
const result: number[] = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
};
const disabledDate: RangePickerProps['disabledDate'] = (current) => {
// Can not select days before today and today
return current && current < dayjs().endOf('day');
};
const disabledDateForMonth: RangePickerProps['disabledDate'] = (current) => {
// Can not select months before this month
return current && current < dayjs().startOf('month');
};
const disabledDateTime = () => ({
disabledHours: () => range(0, 24).splice(4, 20),
disabledMinutes: () => range(30, 60),
disabledSeconds: () => [55, 56],
});
const disabledRangeTime: RangePickerProps['disabledTime'] = (_, type) => {
if (type === 'start') {
return {
disabledHours: () => range(0, 60).splice(4, 20),
disabledMinutes: () => range(30, 60),
disabledSeconds: () => [55, 56],
};
}
return {
disabledHours: () => range(0, 60).splice(20, 4),
disabledMinutes: () => range(0, 31),
disabledSeconds: () => [55, 56],
};
};
const App: React.FC = () => (
);
export default App;
```
### 允许留空
在范围选择时,可以允许留空。这对于需要保留“至今”日期项颇为有用。
```tsx
import React from 'react';
import { DatePicker } from 'antd';
const App: React.FC = () => (
{
console.log(date, dateString);
}}
/>
);
export default App;
```
### 选择不超过一定的范围
使用 `disabledDate` 的 `info.from` 来限制动态的日期区间选择。
```tsx
import React from 'react';
import { DatePicker, Space, Typography } from 'antd';
import type { DatePickerProps } from 'antd';
import type { Dayjs } from 'dayjs';
const { RangePicker } = DatePicker;
const getYearMonth = (date: Dayjs) => date.year() * 12 + date.month();
// Disabled 7 days from the selected date
const disabled7DaysDate: DatePickerProps['disabledDate'] = (current, { from, type }) => {
if (from) {
const minDate = from.add(-6, 'days');
const maxDate = from.add(6, 'days');
switch (type) {
case 'year':
return current.year() < minDate.year() || current.year() > maxDate.year();
case 'month':
return (
getYearMonth(current) < getYearMonth(minDate) ||
getYearMonth(current) > getYearMonth(maxDate)
);
default:
return Math.abs(current.diff(from, 'days')) >= 7;
}
}
return false;
};
// Disabled 6 months from the selected date
const disabled6MonthsDate: DatePickerProps['disabledDate'] = (current, { from, type }) => {
if (from) {
const minDate = from.add(-5, 'months');
const maxDate = from.add(5, 'months');
switch (type) {
case 'year':
return current.year() < minDate.year() || current.year() > maxDate.year();
default:
return (
getYearMonth(current) < getYearMonth(minDate) ||
getYearMonth(current) > getYearMonth(maxDate)
);
}
}
return false;
};
const App: React.FC = () => (
7 days range
6 months range
);
export default App;
```
### 预设范围
可以预设常用的日期范围以提高用户体验。自 `5.8.0` 开始,preset value 支持回调函数返回值方式。
```tsx
import React from 'react';
import type { TimeRangePickerProps } from 'antd';
import { DatePicker, Space } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const { RangePicker } = DatePicker;
const onChange = (date: Dayjs | null) => {
if (date) {
console.log('Date: ', date);
} else {
console.log('Clear');
}
};
const onRangeChange = (dates: null | (Dayjs | null)[], dateStrings: string[]) => {
if (dates) {
console.log('From: ', dates[0], ', to: ', dates[1]);
console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
} else {
console.log('Clear');
}
};
const rangePresets: TimeRangePickerProps['presets'] = [
{ label: 'Last 7 Days', value: [dayjs().add(-7, 'd'), dayjs()] },
{ label: 'Last 14 Days', value: [dayjs().add(-14, 'd'), dayjs()] },
{ label: 'Last 30 Days', value: [dayjs().add(-30, 'd'), dayjs()] },
{ label: 'Last 90 Days', value: [dayjs().add(-90, 'd'), dayjs()] },
];
const App: React.FC = () => (
Now ~ EOD,
value: () => [dayjs(), dayjs().endOf('day')], // 5.8.0+ support function
},
...rangePresets,
]}
showTime
format="YYYY/MM/DD HH:mm:ss"
onChange={onRangeChange}
/>
);
export default App;
```
### 额外的页脚
在浮层中加入额外的页脚,以满足某些定制信息的需求。
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => (
'extra footer'} />
'extra footer'} showTime />
'extra footer'} />
'extra footer'} showTime />
'extra footer'} picker="month" />
);
export default App;
```
### 三种大小
三种大小的输入框,若不设置,则为 `medium`。
```tsx
import React, { useState } from 'react';
import type { ConfigProviderProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio, Space } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const { RangePicker } = DatePicker;
const App: React.FC = () => {
const [size, setSize] = useState('medium');
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
return (
Large
Medium
Small
);
};
export default App;
```
### 定制单元格
使用 `cellRender` 可以自定义单元格的内容和样式。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { DatePicker, Space, theme } from 'antd';
import type { Dayjs } from 'dayjs';
const App: React.FC = () => {
const { token } = theme.useToken();
const style: React.CSSProperties = {
border: `${token.lineWidth}px ${token.lineType} ${token.colorPrimary}`,
borderRadius: '50%',
};
const cellRender: DatePickerProps['cellRender'] = (current, info) => {
if (info.type !== 'date') {
return info.originNode;
}
if (typeof current === 'number' || typeof current === 'string') {
return {current}
;
}
return (
{current.date()}
);
};
return (
);
};
export default App;
```
### 定制面板
通过 `components` 替换对应面板。
```tsx
import React from 'react';
import type { DatePickerProps } from 'antd';
import { Button, DatePicker, Flex, Slider, Space, Typography } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
type DateComponent = Required['components']>>['date'];
type GetProps = T extends React.ComponentType ? P : never;
const MyDatePanel = (props: GetProps) => {
const { value, onSelect, onHover } = props;
// Value
const startDate = React.useMemo(() => dayjs().date(1).month(0), []);
const [innerValue, setInnerValue] = React.useState(value || startDate);
React.useEffect(() => {
if (value) {
setInnerValue(value);
}
}, [value]);
// Range
const dateCount = React.useMemo(() => {
const endDate = startDate.add(1, 'year').add(-1, 'day');
return endDate.diff(startDate, 'day');
}, [startDate]);
const sliderValue = Math.min(Math.max(0, innerValue.diff(startDate, 'day')), dateCount);
// Render
return (
The BEST Picker Panel
{
const nextDate = startDate.add(nextValue, 'day');
setInnerValue(nextDate);
onHover?.(nextDate);
}}
tooltip={{
formatter: (nextValue) => startDate.add(nextValue || 0, 'day').format('YYYY-MM-DD'),
}}
/>
{
onSelect(innerValue);
}}
>{`That's It!`}
);
};
const App: React.FC = () => (
);
export default App;
```
### 外部使用面板
自定义菜单,外置选择面板。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { DatePicker, Dropdown, Space } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
const DatePickerDemo: React.FC = () => {
const [visible, setVisible] = React.useState(false);
const [panelVisible, setPanelVisible] = React.useState(false);
const [date, setDate] = React.useState(() => dayjs());
return (
{
setVisible(open);
if (!open) {
setPanelVisible(false);
}
}}
menu={{
items: [
{
key: 'today',
label: 'Today',
onClick() {
setDate(dayjs());
setVisible(false);
},
},
{
key: 'tomorrow',
label: 'Tomorrow',
onClick() {
setDate(dayjs().add(1, 'day'));
setVisible(false);
},
},
{
key: 'custom-date',
label: (
{
e.stopPropagation();
setPanelVisible(true);
}}
>
Customize
{
e.stopPropagation();
}}
>
{
setDate(date);
setVisible(false);
setPanelVisible(false);
}}
/>
),
},
],
}}
>
{date?.format('YYYY-MM-DD')}
);
};
const RangePickerDemo: React.FC = () => {
const [visible, setVisible] = React.useState(false);
const [panelVisible, setPanelVisible] = React.useState(false);
const [dates, setDates] = React.useState<[Dayjs, Dayjs] | null>(() => [
dayjs(),
dayjs().add(1, 'day'),
]);
return (
{
setVisible(open);
if (!open) {
setPanelVisible(false);
}
}}
menu={{
items: [
{
key: '7',
label: '7 days',
onClick() {
setDates([dayjs(), dayjs().add(7, 'day')]);
setVisible(false);
},
},
{
key: '30',
label: '30 days',
onClick() {
setDates([dayjs(), dayjs().add(30, 'day')]);
setVisible(false);
},
},
{
key: 'custom-date',
label: (
{
e.stopPropagation();
setPanelVisible(true);
}}
>
Customize
{
e.stopPropagation();
}}
>
{
if (ranges?.[0] && ranges?.[1]) {
setDates([ranges[0], ranges[1]]);
} else {
setDates(null);
}
setVisible(false);
setPanelVisible(false);
}}
/>
),
},
],
}}
>
{dates
? `${dates[0].format('YYYY-MM-DD')} ~ ${dates[1].format('YYYY-MM-DD')}`
: 'Select range'}
);
};
const Demo = () => {
return (
);
};
export default Demo;
```
### 佛历格式
通过 `locale` 配置支持特殊的年历格式。
```tsx
import React from 'react';
import { ConfigProvider, DatePicker, Space, Typography } from 'antd';
import type { DatePickerProps } from 'antd';
import en from 'antd/es/date-picker/locale/en_US';
import enUS from 'antd/es/locale/en_US';
import dayjs from 'dayjs';
import buddhistEra from 'dayjs/plugin/buddhistEra';
dayjs.extend(buddhistEra);
const { Title } = Typography;
// Component level locale
const buddhistLocale: typeof en = {
...en,
lang: {
...en.lang,
fieldDateFormat: 'BBBB-MM-DD',
fieldDateTimeFormat: 'BBBB-MM-DD HH:mm:ss',
yearFormat: 'BBBB',
cellYearFormat: 'BBBB',
},
};
// ConfigProvider level locale
const globalBuddhistLocale: typeof enUS = {
...enUS,
DatePicker: {
...enUS.DatePicker!,
lang: buddhistLocale.lang,
},
};
const defaultValue = dayjs('2024-01-01');
const App: React.FC = () => {
const onChange: DatePickerProps['onChange'] = (_, dateStr) => {
console.log('onChange:', dateStr);
};
return (
By locale props
By ConfigProvider
);
};
export default App;
```
### 自定义状态
使用 `status` 为 DatePicker 添加状态,可选 `error` 或者 `warning`。
```tsx
import React from 'react';
import { DatePicker, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 形态变体
DatePicker 形态变体,可选 `outlined` `filled` `borderless` `underlined` 四种形态。
```tsx
import React from 'react';
import { DatePicker, Flex } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 DatePicker 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { DatePicker, Flex } from 'antd';
import type { DatePickerProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
const useStyles = createStyles(({ token }) => ({
root: {
border: `${token.lineWidth}px ${token.lineType} ${token.colorPrimary}`,
width: 200,
},
}));
const stylesObject: DatePickerProps['styles'] = {
input: { fontStyle: 'italic' },
suffix: { opacity: 0.85 },
};
const stylesFn: DatePickerProps['styles'] = (
info,
): GetProp, 'styles', 'Return'> => {
if (info.props.size === 'large') {
return {
root: { borderColor: '#722ed1' },
popup: {
container: { border: '1px solid #722ed1', borderRadius: 8 },
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
### 弹出位置
可以通过 `placement` 手动指定弹出的位置。
```tsx
import React, { useState } from 'react';
import type { DatePickerProps, RadioChangeEvent } from 'antd';
import { DatePicker, Radio } from 'antd';
const { RangePicker } = DatePicker;
const App: React.FC = () => {
const [placement, setPlacement] = useState('topLeft');
const placementChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
topLeft
topRight
bottomLeft
bottomRight
>
);
};
export default App;
```
### 前后缀
自定义前缀 `prefix` 和后缀图标 `suffixIcon`。
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { DatePicker, Space } from 'antd';
import type { Dayjs } from 'dayjs';
const smileIcon = ;
const { RangePicker } = DatePicker;
const onChange = (date: Dayjs | (Dayjs | null)[] | null, dateString: string | string[] | null) => {
console.log(date, dateString);
};
const App: React.FC = () => (
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
日期类组件包括以下五种形式。
- DatePicker
- DatePicker\[picker="month"]
- DatePicker\[picker="week"]
- DatePicker\[picker="year"]
- DatePicker\[picker="quarter"] (4.1.0 新增)
- RangePicker
### 国际化配置
默认配置为 en-US,如果你需要设置其他语言,推荐在入口处使用我们提供的国际化组件,详见:[ConfigProvider 国际化](https://ant.design/components/config-provider-cn/)。
如有特殊需求(仅修改单一组件的语言),请使用 locale 参数,参考:[默认配置](https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json)。
```jsx
// 默认语言为 en-US,如果你需要设置其他语言,推荐在入口文件全局设置 locale
// 确保还导入相关的 dayjs 文件,否则所有文本的区域设置都不会更改(例如范围选择器月份)
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
;
```
:::warning
在搭配 Next.js 的 App Router 使用时,注意在引入 dayjs 的 locale 文件时加上 `'use client'`。这是由于 Ant Design 的组件都是客户端组件,在 RSC 中引入 dayjs 的 locale 文件将不会在客户端生效。
:::
### 共同的 API
以下 API 为 DatePicker、 RangePicker 共享的 API。
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowClear | 自定义清除按钮 | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: 支持对象类型 | 6.4.0 |
| ~~bordered~~ | 是否带边框,请使用 `variant` 替代 | boolean | true | - | × |
| className | 选择器 className | string | - | | DatePicker: 5.7.0,RangePicker: 5.11.0 |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | DatePicker: 5.25.0,RangePicker: 5.25.0 |
| dateRender | 自定义日期单元格的内容,5.4.0 起用 `cellRender` 代替 | function(currentDate: dayjs, today: dayjs) => React.ReactNode | - | < 5.4.0 | × |
| cellRender | 自定义单元格的内容 | (current: dayjs, info: { originNode: React.ReactElement,today: DateType, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| components | 自定义面板 | Record | - | 5.14.0 | × |
| defaultOpen | 是否默认展开控制弹层 | boolean | - | | × |
| disabled | 禁用 | boolean | false | | × |
| disabledDate | 不可选择的日期 | (currentDate: dayjs, info: { from?: dayjs, type: Picker }) => boolean | - | `info`: 5.14.0 | × |
| ~~dropdownClassName~~ | 弹出日历的 className,请使用 `classNames.popup.root` 替代 | string | - | - | × |
| format | 设置日期格式,为数组时支持多格式匹配,展示以第一个为准。配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。示例:[自定义格式](#date-picker-demo-format) | [formatType](#formattype) | [@rc-component/picker](https://github.com/react-component/picker/blob/f512f18ed59d6791280d1c3d7d37abbb9867eb0b/src/utils/uiUtil.ts#L155-L177) | | × |
| order | 多选、范围时是否自动排序 | boolean | true | 5.14.0 | × |
| preserveInvalidOnBlur | 失去焦点是否要清空输入框内无效内容 | boolean | false | 5.14.0 | × |
| ~~popupClassName~~ | 额外的弹出日历 className,使用 `classNames.popup.root` 替代 | string | - | 4.23.0 | × |
| getPopupContainer | 定义浮层的容器,默认为 body 上新建 div | function(trigger) | - | | × |
| inputReadOnly | 设置输入框为只读(避免在移动设备上打开虚拟键盘) | boolean | false | | × |
| locale | 国际化配置 | object | [默认配置](https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json) | | × |
| minDate | 最小日期,同样会限制面板的切换范围 | dayjs | - | 5.14.0 | × |
| maxDate | 最大日期,同样会限制面板的切换范围 | dayjs | - | 5.14.0 | × |
| mode | 日期面板的状态([设置后无法选择年份/月份?](/docs/react/faq#当我指定了-datepickerrangepicker-的-mode-属性后点击后无法选择年份月份)) | `time` \| `date` \| `month` \| `year` \| `decade` | - | | × |
| needConfirm | 是否需要确认按钮,为 `false` 时失去焦点即代表选择。当设置 `multiple` 时默认为 `false` | boolean | - | 5.14.0 | × |
| nextIcon | 自定义下一个图标 | ReactNode | - | 4.17.0 | × |
| open | 控制弹层是否展开 | boolean | - | | × |
| panelRender | 自定义渲染面板 | (panelNode) => ReactNode | - | 4.5.0 | × |
| picker | 设置选择器类型 | `date` \| `week` \| `month` \| `quarter` \| `year` | `date` | `quarter`: 4.1.0 | × |
| placeholder | 输入框提示文字 | string \| \[string, string] | - | | × |
| placement | 选择框弹出的位置 | `bottomLeft` `bottomRight` `topLeft` `topRight` | bottomLeft | | × |
| ~~popupStyle~~ | 额外的弹出日历样式,使用 `styles.popup.root` 替代 | CSSProperties | {} | | × |
| prefix | 自定义前缀 | ReactNode | - | 5.22.0 | × |
| prevIcon | 自定义上一个图标 | ReactNode | - | 4.17.0 | × |
| previewValue | 当用户选择日期悬停选项时,输入字段的值会发生临时更改 | false \| hover | hover | 6.0.0 | × |
| presets | 预设时间范围快捷选择, 自 `5.8.0` 起 value 支持函数返回值 | { label: React.ReactNode, value: Dayjs \| (() => Dayjs) }\[] | - | | × |
| size | 输入框大小,`large` 高度为 40px,`small` 为 24px,默认是 32px | `large` \| `medium` \| `small` | - | | × |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 | × |
| style | 自定义输入框样式 | CSSProperties | {} | | DatePicker: 5.7.0,RangePicker: 5.11.0 |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | DatePicker: 5.25.0,RangePicker: 5.25.0 |
| suffixIcon | 自定义的选择框后缀图标 | ReactNode | - | | DatePicker: 6.3.0,RangePicker: 6.4.0 |
| superNextIcon | 自定义 `>>` 切换图标 | ReactNode | - | 4.17.0 | × |
| superPrevIcon | 自定义 `<<` 切换图标 | ReactNode | - | 4.17.0 | × |
| clearIcon | (仅支持全局配置)自定义清除图标 | ReactNode | - | × | 6.4.0 |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | DatePicker: 5.19.0,RangePicker: 5.19.0 |
| onClear | 点击清除按钮时的回调 | () => void | - | 6.5.0 | × |
| onOpenChange | 弹出日历和关闭日历的回调 | function(open) | - | | × |
| onPanelChange | 日历面板切换的回调 | function(value, mode) | - | | × |
| ~~onSelect~~ | 选中日期时的回调,请使用 `onCalendarChange` 替代 | function(value) | - | - | × |
### 共同的方法
| 名称 | 描述 | 版本 |
| ------- | -------- | ---- |
| blur() | 移除焦点 | |
| focus() | 获取焦点 | |
### DatePicker
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| defaultPickerValue | 默认面板日期,每次面板打开时会被重置到该日期 | [dayjs](https://day.js.org/) | - | 5.14.0 |
| defaultValue | 默认日期,如果开始时间或结束时间为 `null` 或者 `undefined`,日期范围将是一个开区间 | [dayjs](https://day.js.org/) | - | |
| disabledTime | 不可选择的时间 | function(date) | - | |
| format | 展示的日期格式,配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。 | [formatType](#formattype) | `YYYY-MM-DD` | |
| multiple | 是否为多选,不支持 `showTime` | boolean | false | 5.14.0 |
| pickerValue | 面板日期,可以用于受控切换面板所在日期。配合 `onPanelChange` 使用。 | [dayjs](https://day.js.org/) | - | 5.14.0 |
| renderExtraFooter | 在面板中添加额外的页脚 | (mode) => React.ReactNode | - | |
| showNow | 显示当前日期时间的快捷选择 | boolean | - | |
| showTime | 增加时间选择功能 | Object \| boolean | [TimePicker Options](/components/time-picker-cn#api) | |
| ~~showTime.defaultValue~~ | 请使用 `showTime.defaultOpenValue` | [dayjs](https://day.js.org/) | dayjs() | 5.27.3 |
| showTime.defaultOpenValue | 设置用户选择日期时默认的时分秒,[例子](#date-picker-demo-disabled-date) | [dayjs](https://day.js.org/) | dayjs() | |
| showWeek | DatePicker 下展示当前周 | boolean | false | 5.14.0 |
| value | 日期 | [dayjs](https://day.js.org/) | - | |
| onChange | 时间发生变化的回调 | function(date: dayjs \| null, dateString: string \| null) | - | |
| onOk | 点击确定按钮的回调 | function() | - | |
| onPanelChange | 日期面板变化时的回调 | function(value, mode) | - | |
### DatePicker\[picker=year]
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| defaultValue | 默认日期 | [dayjs](https://day.js.org/) | - | |
| format | 展示的日期格式,配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。 | [formatType](#formattype) | `YYYY` | |
| multiple | 是否为多选 | boolean | false | 5.14.0 |
| renderExtraFooter | 在面板中添加额外的页脚 | () => React.ReactNode | - | |
| tagRender | 自定义 tag 内容 render,仅在 `multiple` 模式下生效 | (props) => ReactNode | - | 6.4.0 |
| value | 日期 | [dayjs](https://day.js.org/) | - | |
| onChange | 时间发生变化的回调,发生在用户选择时间时 | function(date: dayjs \| null, dateString: string \| null) | - | |
### DatePicker\[picker=quarter]
`4.1.0` 新增。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| defaultValue | 默认日期 | [dayjs](https://day.js.org/) | - | |
| format | 展示的日期格式,配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。 | [formatType](#formattype) | `YYYY-\QQ` | |
| multiple | 是否为多选 | boolean | false | 5.14.0 |
| renderExtraFooter | 在面板中添加额外的页脚 | () => React.ReactNode | - | |
| tagRender | 自定义 tag 内容 render,仅在 `multiple` 模式下生效 | (props) => ReactNode | - | 6.4.0 |
| value | 日期 | [dayjs](https://day.js.org/) | - | |
| onChange | 时间发生变化的回调,发生在用户选择时间时 | function(date: dayjs \| null, dateString: string \| null) | - | |
### DatePicker\[picker=month]
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| defaultValue | 默认日期 | [dayjs](https://day.js.org/) | - | |
| format | 展示的日期格式,配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。 | [formatType](#formattype) | `YYYY-MM` | |
| multiple | 是否为多选 | boolean | false | 5.14.0 |
| renderExtraFooter | 在面板中添加额外的页脚 | () => React.ReactNode | - | |
| tagRender | 自定义 tag 内容 render,仅在 `multiple` 模式下生效 | (props) => ReactNode | - | 6.4.0 |
| value | 日期 | [dayjs](https://day.js.org/) | - | |
| onChange | 时间发生变化的回调,发生在用户选择时间时 | function(date: dayjs \| null, dateString: string \| null) | - | |
### DatePicker\[picker=week]
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| defaultValue | 默认日期 | [dayjs](https://day.js.org/) | - | |
| format | 展示的日期格式,配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。 | [formatType](#formattype) | `YYYY-wo` | |
| multiple | 是否为多选 | boolean | false | 5.14.0 |
| renderExtraFooter | 在面板中添加额外的页脚 | (mode) => React.ReactNode | - | |
| tagRender | 自定义 tag 内容 render,仅在 `multiple` 模式下生效 | (props) => ReactNode | - | 6.4.0 |
| value | 日期 | [dayjs](https://day.js.org/) | - | |
| onChange | 时间发生变化的回调,发生在用户选择时间时 | function(date: dayjs \| null, dateString: string \| null) | - | |
| showWeek | DatePicker 下展示当前周 | boolean | true | 5.14.0 |
### RangePicker
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| allowEmpty | 允许起始项部分为空 | \[boolean, boolean] | \[false, false] | | × |
| cellRender | 自定义单元格的内容。 | (current: dayjs, info: { originNode: React.ReactElement,today: DateType, range?: 'start' \| 'end', type: PanelMode, locale?: Locale, subType?: 'hour' \| 'minute' \| 'second' \| 'meridiem' }) => React.ReactNode | - | 5.4.0 | × |
| dateRender | 自定义日期单元格的内容,5.4.0 起用 `cellRender` 代替 | function(currentDate: dayjs, today: dayjs) => React.ReactNode | - | < 5.4.0 | × |
| defaultPickerValue | 默认面板日期,每次面板打开时会被重置到该日期 | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | 5.14.0 | × |
| defaultValue | 默认日期 | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | | × |
| disabled | 禁用起始项 | \[boolean, boolean] | - | | × |
| disabledTime | 不可选择的时间 | function(date: dayjs, partial: `start` \| `end`, info: { from?: dayjs }) | - | `info.from`: 5.17.0 | × |
| format | 展示的日期格式,配置参考 [dayjs#format](https://day.js.org/docs/zh-CN/display/format#%E6%94%AF%E6%8C%81%E7%9A%84%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%8D%A0%E4%BD%8D%E7%AC%A6%E5%88%97%E8%A1%A8)。 | [formatType](#formattype) | `YYYY-MM-DD HH:mm:ss` | | × |
| id | 设置输入框 `id` 属性。 | { start?: string, end?: string } | - | 5.14.0 | × |
| pickerValue | 面板日期,可以用于受控切换面板所在日期。配合 `onPanelChange` 使用。 | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | 5.14.0 | × |
| presets | 预设时间范围快捷选择,自 `5.8.0` 起 value 支持函数返回值 | { label: React.ReactNode, value: \[(Dayjs \| (() => Dayjs)), (Dayjs \| (() => Dayjs))] }\[] | - | | × |
| renderExtraFooter | 在面板中添加额外的页脚 | () => React.ReactNode | - | | × |
| separator | 设置分隔符 | React.ReactNode | ` ` | | 6.3.0 |
| showTime | 增加时间选择功能 | Object\|boolean | [TimePicker Options](/components/time-picker-cn#api) | | × |
| ~~showTime.defaultValue~~ | 请使用 `showTime.defaultOpenValue` | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | \[dayjs(), dayjs()] | 5.27.3 | × |
| showTime.defaultOpenValue | 设置用户选择日期时默认的时分秒,[例子](#date-picker-demo-disabled-date) | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | \[dayjs(), dayjs()] | | × |
| value | 日期 | \[[dayjs](https://day.js.org/), [dayjs](https://day.js.org/)] | - | | × |
| onCalendarChange | 待选日期发生变化的回调。`info` 参数自 4.4.0 添加 | function(dates: \[dayjs, dayjs], dateStrings: \[string, string], info: { range:`start`\|`end` }) | - | | × |
| onChange | 日期范围发生变化的回调 | function(dates: \[dayjs, dayjs] \| null, dateStrings: \[string, string] \| null) | - | | × |
| onFocus | 聚焦时回调 | function(event, { range: 'start' \| 'end' }) | - | `range`: 5.14.0 | × |
| onBlur | 失焦时回调 | function(event, { range: 'start' \| 'end' }) | - | `range`: 5.14.0 | × |
#### formatType
```typescript
import type { Dayjs } from 'dayjs';
type Generic = string;
type GenericFn = (value: Dayjs) => string;
export type FormatType =
| Generic
| GenericFn
| Array
| {
format: string;
type?: 'mask';
};
```
注意:`type` 定义为 `5.14.0` 新增。
## Semantic DOM
https://ant.design/components/date-picker-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (DatePicker)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| activeBg | 输入框激活状态时背景颜色 | string | #ffffff |
| activeBorderColor | 激活态边框色 | string | #1677ff |
| activeShadow | 激活态阴影 | string | 0 0 0 2px rgba(5,145,255,0.1) |
| addonBg | 前/后置标签背景色 | string | rgba(0,0,0,0.02) |
| cellActiveWithRangeBg | 选取范围内的单元格背景色 | string | #e6f4ff |
| cellBgDisabled | 单元格禁用态背景色 | string | rgba(0,0,0,0.04) |
| cellHeight | 单元格高度 | number | 24 |
| cellHoverBg | 单元格悬浮态背景色 | string | rgba(0,0,0,0.04) |
| cellHoverWithRangeBg | 选取范围内的单元格悬浮态背景色 | string | #cbe0fd |
| cellRangeBorderColor | 选取范围时单元格边框色 | string | #82b4f9 |
| cellWidth | 单元格宽度 | number | 36 |
| errorActiveShadow | 错误状态时激活态阴影 | string | 0 0 0 2px rgba(255,38,5,0.06) |
| hoverBg | 输入框hover状态时背景颜色 | string | #ffffff |
| hoverBorderColor | 悬浮态边框色 | string | #4096ff |
| inputFontSize | 字体大小 | number | 14 |
| inputFontSizeLG | 大号字体大小 | number | 16 |
| inputFontSizeSM | 小号字体大小 | number | 14 |
| multipleItemBg | 多选标签背景色 | string | rgba(0,0,0,0.06) |
| multipleItemBorderColor | 多选标签边框色 | string | transparent |
| multipleItemBorderColorDisabled | 多选标签禁用边框色 | string | transparent |
| multipleItemColorDisabled | 多选标签禁用文本颜色 | string | rgba(0,0,0,0.25) |
| multipleItemHeight | 多选标签高度 | number | 24 |
| multipleItemHeightLG | 大号多选标签高度 | number | 32 |
| multipleItemHeightSM | 小号多选标签高度 | number | 16 |
| multipleSelectorBgDisabled | 多选框禁用背景 | string | rgba(0,0,0,0.04) |
| paddingBlock | 输入框纵向内边距 | number | 4 |
| paddingBlockLG | 大号输入框纵向内边距 | number | 7 |
| paddingBlockSM | 小号输入框纵向内边距 | number | 0 |
| paddingInline | 输入框横向内边距 | number | 11 |
| paddingInlineLG | 大号输入框横向内边距 | number | 11 |
| paddingInlineSM | 小号输入框横向内边距 | number | 7 |
| presetsMaxWidth | 预设区域最大宽度 | number | 200 |
| presetsWidth | 预设区域宽度 | number | 120 |
| textHeight | 单元格文本高度 | number | 40 |
| timeCellHeight | 时间单元格高度 | number | 28 |
| timeColumnHeight | 时间列高度 | number | 224 |
| timeColumnWidth | 时间列宽度 | number | 56 |
| warningActiveShadow | 警告状态时激活态阴影 | string | 0 0 0 2px rgba(255,215,5,0.1) |
| withoutTimeCellHeight | 十年/年/季/月/周单元格高度 | number | 66 |
| zIndexPopup | 弹窗 z-index | number | 1050 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| boxShadowSecondary | 控制元素二级阴影样式。 | string | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorBorderDisabled | 控制元素在禁用状态下的边框颜色。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorAffix | 控制表单控件前后缀在错误状态下的颜色。 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBgHover | 错误色的浅色背景色悬浮态 | string | |
| colorErrorBorderHover | 错误色的描边色悬浮态 | string | |
| colorErrorText | 错误色的文本默认态 | string | |
| colorFillSecondary | 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 | string | |
| colorFillTertiary | 三级填充色用于勾勒出元素形体的场景,如 Slider、Segmented 等。如无强调需求的情况下,建议使用三级填色作为默认填色。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextPlaceholder | 控制占位文本的颜色。 | string | |
| colorTextQuaternary | 第四级文本色是最浅的文本色,例如表单的输入提示文本、禁用色文本等。 | string | |
| colorTextTertiary | 第三级文本色一般用于描述性文本,例如表单的中的补充说明文本、列表的描述性文本等场景。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| colorWarningAffix | 控制表单控件前后缀在警告状态下的颜色。 | string | |
| colorWarningBg | 警戒色的浅色背景颜色 | string | |
| colorWarningBgHover | 警戒色的浅色背景色悬浮态 | string | |
| colorWarningBorderHover | 警戒色的描边色悬浮态 | string | |
| colorWarningText | 警戒色的文本默认态 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| controlItemBgActive | 控制组件项在激活状态下的背景颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| fontSizeSM | 小号字体大小 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| motionEaseInQuint | 预设动效曲率 | string | |
| motionEaseOutCirc | 预设动效曲率 | string | |
| motionEaseOutQuint | 预设动效曲率 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingSM | 控制元素的小内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
| sizePopupArrow | 组件箭头的尺寸 | number | |
## FAQ
### 当我指定了 DatePicker/RangePicker 的 mode 属性后,点击后无法选择年份/月份? {#faq-mode-cannot-select}
请参考[常见问答](/docs/react/faq#当我指定了-datepickerrangepicker-的-mode-属性后点击后无法选择年份月份)
### 为何日期选择年份后返回的是日期面板而不是月份面板? {#faq-year-to-date-panel}
当用户选择完年份后,系统会直接切换至日期面板,而非显式提供月份选择。这样做的设计在于用户只需进行一次点击即可完成年份修改,无需再次点击进入月份选择界面,从而减少了用户的操作负担,同时也避免需要额外感知月份的记忆负担。
### 如何在 DatePicker 中使用自定义日期库(如 Moment.js )? {#faq-custom-date-library}
请参考[《使用自定义日期库》](/docs/react/use-custom-date-library#datepicker)
### 为什么时间类组件的国际化 locale 设置不生效? {#faq-locale-not-work}
参考 FAQ [为什么时间类组件的国际化 locale 设置不生效?](/docs/react/faq#为什么时间类组件的国际化-locale-设置不生效)。
### 如何修改周的起始日? {#faq-week-start-day}
请使用正确的[语言包](/docs/react/i18n-cn)([#5605](https://github.com/ant-design/ant-design/issues/5605)),或者修改 dayjs 的 `locale` 配置:
```js
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import updateLocale from 'dayjs/plugin/updateLocale';
dayjs.extend(updateLocale);
dayjs.updateLocale('zh-cn', {
weekStart: 0,
});
```
### 为何使用 `panelRender` 时,原来面板无法切换? {#faq-panel-render-switch}
当你通过 `panelRender` 动态改变层级结构时,会使得原本的 Panel 被当做新的节点删除并创建。这使得其原本的状态会被重置,保持结构稳定即可。详情请参考 [#27263](https://github.com/ant-design/ant-design/issues/27263)。
### 如何理解禁用时间日期? {#faq-disabled-date-time}
欢迎阅读博客[《为什么禁用日期这么难?》](/docs/blog/picker-cn)了解如何使用。
---
## descriptions-cn
Source: https://ant.design/components/descriptions-cn.md
---
category: Components
group: 数据展示
title: Descriptions
subtitle: 描述列表
description: 展示多个只读字段的组合。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*fHdlTpif6XQAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*d27AQJrowGAAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
常见于详情页的信息展示。
```tsx | pure
// >= 5.8.0 可用,推荐的写法 ✅
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'UserName',
children: Zhou Maomao
,
},
{
key: '2',
label: 'Telephone',
children: 1810000000
,
},
{
key: '3',
label: 'Live',
children: Hangzhou, Zhejiang
,
},
{
key: '4',
label: 'Remark',
children: empty
,
},
{
key: '5',
label: 'Address',
children: No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China
,
},
];
;
// <5.8.0 可用,>=5.8.0 时不推荐 🙅🏻♀️
Zhou Maomao
1810000000
Hangzhou, Zhejiang
empty
No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China
;
```
## 代码演示 {#examples}
### 基本
简单的展示。
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'UserName',
children: 'Zhou Maomao',
},
{
key: '2',
label: 'Telephone',
children: '1810000000',
},
{
key: '3',
label: 'Live',
children: 'Hangzhou, Zhejiang',
},
{
key: '4',
label: 'Remark',
children: 'empty',
},
{
key: '5',
label: 'Address',
children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China',
},
];
const App: React.FC = () => ;
export default App;
```
### 带边框的
带边框和背景颜色列表。
```tsx
import React from 'react';
import { Badge, Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing Mode',
children: 'Prepaid',
},
{
key: '3',
label: 'Automatic Renewal',
children: 'YES',
},
{
key: '4',
label: 'Order time',
children: '2018-04-24 18:00:00',
},
{
key: '5',
label: 'Usage Time',
children: '2019-04-24 18:00:00',
span: 2,
},
{
key: '6',
label: 'Status',
children: ,
span: 3,
},
{
key: '7',
label: 'Negotiated Amount',
children: '$80.00',
},
{
key: '8',
label: 'Discount',
children: '$20.00',
},
{
key: '9',
label: 'Official Receipts',
children: '$60.00',
},
{
key: '10',
label: 'Config Info',
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const App: React.FC = () => ;
export default App;
```
### 自定义尺寸
自定义尺寸,适应在各种容器中展示。
```tsx
import React, { useState } from 'react';
import { Button, Descriptions, Radio } from 'antd';
import type { DescriptionsProps, RadioChangeEvent } from 'antd';
const borderedItems: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing',
children: 'Prepaid',
},
{
key: '3',
label: 'Time',
children: '18:00:00',
},
{
key: '4',
label: 'Amount',
children: '$80.00',
},
{
key: '5',
label: 'Discount',
children: '$20.00',
},
{
key: '6',
label: 'Official',
children: '$60.00',
},
{
key: '7',
label: 'Config Info',
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing',
children: 'Prepaid',
},
{
key: '3',
label: 'Time',
children: '18:00:00',
},
{
key: '4',
label: 'Amount',
children: '$80.00',
},
{
key: '5',
label: 'Discount',
children: '$20.00',
},
{
key: '6',
label: 'Official',
children: '$60.00',
},
];
const App: React.FC = () => {
const [size, setSize] = useState<'large' | 'medium' | 'small'>('large');
const onChange = (e: RadioChangeEvent) => {
console.log('size checked', e.target.value);
setSize(e.target.value);
};
return (
large
medium
small
Edit}
items={borderedItems}
/>
Edit}
items={items}
/>
);
};
export default App;
```
### 响应式
通过响应式的配置可以实现在小屏幕设备上的完美呈现。
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
label: 'Product',
children: 'Cloud Database',
},
{
label: 'Billing',
children: 'Prepaid',
},
{
label: 'Time',
children: '18:00:00',
},
{
label: 'Amount',
children: '$80.00',
},
{
label: 'Discount',
span: { xl: 2, xxl: 2 },
children: '$20.00',
},
{
label: 'Official',
span: { xl: 2, xxl: 2 },
children: '$60.00',
},
{
label: 'Config Info',
span: { xs: 1, sm: 2, md: 3, lg: 3, xl: 2, xxl: 2 },
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
>
),
},
{
label: 'Hardware Info',
span: { xs: 1, sm: 2, md: 3, lg: 3, xl: 2, xxl: 2 },
children: (
<>
CPU: 6 Core 3.5 GHz
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const App: React.FC = () => (
);
export default App;
```
### 垂直
垂直的列表。
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'UserName',
children: 'Zhou Maomao',
},
{
key: '2',
label: 'Telephone',
children: '1810000000',
},
{
key: '3',
label: 'Live',
children: 'Hangzhou, Zhejiang',
},
{
key: '4',
label: 'Address',
span: 2,
children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China',
},
{
key: '5',
label: 'Remark',
children: 'empty',
},
];
const App: React.FC = () => ;
export default App;
```
### 垂直带边框的
垂直带边框和背景颜色的列表。
```tsx
import React from 'react';
import { Badge, Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing Mode',
children: 'Prepaid',
},
{
key: '3',
label: 'Automatic Renewal',
children: 'YES',
},
{
key: '4',
label: 'Order time',
children: '2018-04-24 18:00:00',
},
{
key: '5',
label: 'Usage Time',
span: 2,
children: '2019-04-24 18:00:00',
},
{
key: '6',
label: 'Status',
span: 3,
children: ,
},
{
key: '7',
label: 'Negotiated Amount',
children: '$80.00',
},
{
key: '8',
label: 'Discount',
children: '$20.00',
},
{
key: '9',
label: 'Official Receipts',
children: '$60.00',
},
{
key: '10',
label: 'Config Info',
children: (
<>
Data disk type: MongoDB
Database version: 3.4
Package: dds.mongo.mid
Storage space: 10 GB
Replication factor: 3
Region: East China 1
>
),
},
];
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Descriptions 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Descriptions, Flex } from 'antd';
import type { DescriptionsProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 10px;
`,
}));
const items: DescriptionsProps['items'] = [
{
key: '1',
label: 'Product',
children: 'Cloud Database',
},
{
key: '2',
label: 'Billing Mode',
children: 'Prepaid',
},
{
key: '3',
label: 'Automatic Renewal',
children: 'YES',
},
];
const styles: DescriptionsProps['styles'] = {
label: {
color: '#000',
},
};
const stylesFn: DescriptionsProps['styles'] = (
info,
): GetProp => {
if (info.props.size === 'large') {
return {
root: {
borderRadius: 8,
border: '1px solid #CDC1FF',
},
label: { color: '#A294F9' },
};
}
return {};
};
const App: React.FC = () => {
const descriptionsProps: DescriptionsProps = {
title: 'User Info',
items,
bordered: true,
classNames,
};
return (
);
};
export default App;
```
### 整行
整行的展示。
```tsx
import React from 'react';
import { Descriptions } from 'antd';
import type { DescriptionsProps } from 'antd';
const items: DescriptionsProps['items'] = [
{
label: 'UserName',
children: 'Zhou Maomao',
},
{
label: 'Live',
span: 'filled', // span = 2
children: 'Hangzhou, Zhejiang',
},
{
label: 'Remark',
span: 'filled', // span = 3
children: 'empty',
},
{
label: 'Address',
span: 1, // span will be 3 and warning for span is not align to the end
children: 'No. 18, Wantang Road, Xihu District, Hangzhou, Zhejiang, China',
},
];
const App: React.FC = () => ;
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Descriptions
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| bordered | 是否展示边框 | boolean | false | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.23.0 |
| colon | 配置 `Descriptions.Item` 的 `colon` 的默认值。表示是否显示 label 后面的冒号 | boolean | true | | × |
| column | 一行的 `DescriptionItems` 数量,可以写成像素值或支持响应式的对象写法 `{ xs: 8, sm: 16, md: 24}` | number \| [Record](https://github.com/ant-design/ant-design/blob/84ca0d23ae52e4f0940f20b0e22eabe743f90dca/components/descriptions/index.tsx#L111C21-L111C56) | 3 | | × |
| ~~contentStyle~~ | 自定义内容样式,请使用 `styles.content` 替换 | CSSProperties | - | 4.10.0 | × |
| extra | 描述列表的操作区域,显示在右上方 | ReactNode | - | 4.5.0 | × |
| items | 描述列表项内容 | [DescriptionsItem](#descriptionitem)[] | - | 5.8.0 | × |
| ~~labelStyle~~ | 自定义标签样式,请使用 `styles.label` 替换 | CSSProperties | - | 4.10.0 | × |
| layout | 描述布局 | `horizontal` \| `vertical` | `horizontal` | | × |
| size | 设置列表的大小。可以设置为 `medium` 、`small`, 或不填 | `large` \| `medium` \| `small` | `large` | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.23.0 |
| title | 描述列表的标题,显示在最顶部 | ReactNode | - | | × |
### DescriptionItem
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| ~~contentStyle~~ | 自定义内容样式,请使用 `styles.content` 替换 | CSSProperties | - | 4.9.0 |
| label | 内容的描述 | ReactNode | - | |
| ~~labelStyle~~ | 自定义标签样式,请使用 `styles.label` 替换 | CSSProperties | - | 4.9.0 |
| span | 包含列的数量(`filled` 铺满当前行剩余部分) | number\| `filled` \| [Screens](/components/grid-cn#col) | 1 | `screens: 5.9.0`,`filled: 5.22.0` |
> span 是 Description.Item 的数量。 span={2} 会占用两个 DescriptionItem 的宽度。当同时配置 `style` 和 `labelStyle`(或 `contentStyle`)时,两者会同时作用。样式冲突时,后者会覆盖前者。
## Semantic DOM
https://ant.design/components/descriptions-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Descriptions)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colonMarginLeft | 冒号左间距 | number | 2 |
| colonMarginRight | 冒号右间距 | number | 8 |
| contentColor | 内容区域文字颜色 | string | rgba(0,0,0,0.88) |
| extraColor | 额外区域文字颜色 | string | rgba(0,0,0,0.88) |
| itemPaddingBottom | 子项下间距 | number | 16 |
| itemPaddingEnd | 子项结束间距 | number | 16 |
| labelBg | 标签背景色 | string | rgba(0,0,0,0.02) |
| labelColor | 标签文字颜色 | string | rgba(0,0,0,0.45) |
| titleColor | 标题文字颜色 | string | rgba(0,0,0,0.88) |
| titleMarginBottom | 标题下间距 | number | 20 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextSecondary | 作为第二梯度的文本色,一般用在不那么需要强化文本颜色的场景,例如 Label 文本、Menu 的文本选中态等场景。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingSM | 控制元素的小内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## divider-cn
Source: https://ant.design/components/divider-cn.md
---
category: Components
title: Divider
subtitle: 分割线
description: 区隔内容的分割线。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*7sMiTbzvaDoAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*KPSEQ74PLg4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 布局
order: 2
---
## 何时使用 {#when-to-use}
- 对不同章节的文本段落进行分割。
- 对行内文字/链接进行分割,例如表格的操作列。
## 代码演示 {#examples}
### 水平分割线
默认为水平分割线,可在中间加入文字。
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### 带文字的分割线
分割线中带有文字,可以用 `titlePlacement` 指定文字位置。
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Left Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Right Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Left Text margin with 0
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Right Text margin with 50px
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### 设置分割线的间距大小
间距的大小。
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### 分割文字使用正文样式
使用 `plain` 可以设置为更轻量的分割文字样式。
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Left Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Right Text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### 垂直分割线
使用 `orientation="vertical"` 或者 `vertical` 设置为行内的垂直分割线。
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Text
Link
Link
>
);
export default App;
```
### 变体
分隔线默认为 `solid`(实线)变体。您可以将其更改为 `dashed`(虚线)或 `dotted`(点线)。
```tsx
import React from 'react';
import { Divider } from 'antd';
const App: React.FC = () => (
<>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Solid
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Dotted
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
Dashed
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nonne merninisti licere mihi ista
probare, quae sunt a te dicta? Refert tamen, quo modo.
>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义分割线的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Divider } from 'antd';
import type { DividerProps, GetProp } from 'antd';
const classNamesObject: DividerProps['classNames'] = {
root: 'demo-divider-root',
content: 'demo-divider-content',
rail: 'demo-divider-rail',
};
const classNamesFn: DividerProps['classNames'] = (
info,
): GetProp => {
if (info.props.titlePlacement === 'start') {
return {
root: 'demo-divider-root--start',
};
}
return {
root: 'demo-divider-root--default',
};
};
const stylesObject: DividerProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed' },
content: { fontStyle: 'italic' },
rail: { opacity: 0.85 },
};
const stylesFn: DividerProps['styles'] = (info): GetProp => {
if (info.props.size === 'small') {
return {
root: { opacity: 0.6, cursor: 'default' },
};
}
return {
root: { backgroundColor: '#fafafa', borderColor: '#d9d9d9' },
};
};
const App: React.FC = () => (
classNames Object
classNames Function
styles Object
styles Function
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| children | 嵌套的标题 | ReactNode | - | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| dashed | 是否虚线 | boolean | false | | × |
| orientation | 水平或垂直类型 | `horizontal` \| `vertical` | `horizontal` | - | × |
| ~~orientationMargin~~ | 标题和最近 left/right 边框之间的距离,去除了分割线,同时 `titlePlacement` 不能为 `center`。如果传入 `string` 类型的数字且不带单位,默认单位是 px | string \| number | - | | × |
| plain | 文字是否显示为普通正文样式 | boolean | false | 4.2.0 | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| size | 间距大小,仅对水平布局有效 | `small` \| `medium` \| `large` | - | 5.25.0 | × |
| titlePlacement | 分割线标题的位置 | `start` \| `end` \| `center` | `center` | - | × |
| ~~type~~ | 水平还是垂直类型 | `horizontal` \| `vertical` | `horizontal` | - | × |
| variant | 分割线是虚线、点线还是实线 | `dashed` \| `dotted` \| `solid` | solid | 5.20.0 | × |
| vertical | 是否垂直,和 orientation 同时配置以 orientation 优先 | boolean | false | - | × |
## Semantic DOM
https://ant.design/components/divider-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Divider)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| orientationMargin | 文本与边缘距离,取值 0 ~ 1 | number | 0.05 |
| textPaddingInline | 文本横向内间距 | PaddingInline \| undefined | 1em |
| verticalMarginInline | 纵向分割线的横向外间距 | MarginInline \| undefined | 8 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginLG | 控制元素外边距,大尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
---
## drawer-cn
Source: https://ant.design/components/drawer-cn.md
---
group: 反馈
category: Components
title: Drawer
subtitle: 抽屉
description: 屏幕边缘滑出的浮层面板。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*BD2JSKm8I-kAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*r29rQ51bNdwAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
抽屉从父窗体边缘滑入,覆盖住部分父窗体内容。用户在抽屉内操作时不必离开当前任务,操作完成后,可以平滑地回到原任务。
- 当需要一个附加的面板来控制父窗体内容,这个面板在需要时呼出。比如,控制界面展示样式,往界面中添加内容。
- 当需要在当前任务流中插入临时任务,创建或预览附加内容。比如展示协议条款,创建子对象。
> 开发者注意事项:
>
> 自 `5.17.0` 版本,我们提供了 `loading` 属性,内置 Spin 组件作为加载状态,但是自 `5.18.0` 版本开始,我们修复了设计失误,将内置的 Spin 组件替换成了 Skeleton 组件,同时收窄了 `loading` api 的类型范围,只能接收 boolean 类型。
## 代码演示 {#examples}
### 基础抽屉
基础抽屉,点击触发按钮抽屉从右滑出,点击遮罩区关闭。
```tsx
import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
Open
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 自定义位置
自定义位置,点击触发按钮抽屉从相应的位置滑出,点击遮罩区关闭。
```tsx
import React, { useState } from 'react';
import type { DrawerProps, RadioChangeEvent } from 'antd';
import { Button, Drawer, Radio, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('left');
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
const onChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
return (
<>
top
right
bottom
left
Open
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 可调整大小
可调整大小的抽屉,允许通过拖拽边缘来调整抽屉的宽度或高度。
```tsx
import React, { useState } from 'react';
import type { DrawerProps, RadioChangeEvent } from 'antd';
import { Button, Drawer, Radio, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('right');
const [size, setSize] = useState(256);
const onChange = (e: RadioChangeEvent) => {
setSize(256);
setPlacement(e.target.value);
};
return (
<>
({
label: pos,
value: pos,
}))}
/>
setOpen(true)}>
Open Drawer
Current size: {size}px
setOpen(false)}
open={open}
key={placement}
size={size}
resizable={{
onResize: (newSize) => setSize(newSize),
}}
>
Drag the edge to resize the drawer
Current size: {size}px
>
);
};
export default App;
```
### 加载中
设置抽屉加载状态。
```tsx
import React from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = React.useState(false);
const [loading, setLoading] = React.useState(true);
const showLoading = () => {
setOpen(true);
setLoading(true);
// Simple loading mock. You should add cleanup logic in real world.
setTimeout(() => {
setLoading(false);
}, 2000);
};
return (
<>
Open Drawer
Loading Drawer}
placement="right"
open={open}
loading={loading}
onClose={() => setOpen(false)}
>
Reload
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 额外操作
在 Ant Design 规范中,操作按钮建议放在抽屉的右上角,可以使用 `extra` 属性来实现。
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Radio, Space } from 'antd';
import type { DrawerProps, RadioChangeEvent } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [placement, setPlacement] = useState('right');
const showDrawer = () => {
setOpen(true);
};
const onChange = (e: RadioChangeEvent) => {
setPlacement(e.target.value);
};
const onClose = () => {
setOpen(false);
};
return (
<>
top
right
bottom
left
Open
Cancel
OK
}
>
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 渲染在当前 DOM
渲染在当前 dom 里。自定义容器,查看 `getContainer`。
> 注意:在 v5 中 `style` 与 `className` 迁移至 Drawer 面板上与 Modal 保持一致,原 `style` 与 `className` 替换为 `rootStyle` 与 `rootClassName`。
> 当 `getContainer` 返回 DOM 节点时,需要手动设置 `rootStyle` 为 `{ position: 'absolute' }`,参考 [#41951](https://github.com/ant-design/ant-design/issues/41951#issuecomment-1521099152)。
```tsx
import React, { useState } from 'react';
import { Button, Drawer, theme } from 'antd';
const App: React.FC = () => {
const { token } = theme.useToken();
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
const containerStyle: React.CSSProperties = {
position: 'relative',
height: 200,
padding: 48,
overflow: 'hidden',
background: token.colorFillAlter,
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorderSecondary}`,
borderRadius: token.borderRadiusLG,
};
return (
Render in this
Open
Some contents...
);
};
export default App;
```
### 抽屉表单
在抽屉中使用表单。
```tsx
import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Col, DatePicker, Drawer, Form, Input, Row, Select, Space } from 'antd';
import type { InputProps } from 'antd';
const UrlInput: React.FC = (props) => {
return (
http://
.com
);
};
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
}>
New account
Cancel
Submit
}
>
>
);
};
export default App;
```
### 信息预览抽屉
需要快速预览对象概要时使用,点击遮罩区关闭。
```tsx
import React, { useState } from 'react';
import { Avatar, Col, Divider, Drawer, List, Row } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css, cssVar } = props;
return {
descriptionItem: css`
margin-bottom: ${cssVar.marginXS};
color: ${cssVar.colorTextLabel};
font-size: ${cssVar.fontSize};
line-height: ${cssVar.lineHeight};
`,
profileTitle: css`
display: block;
margin-bottom: ${cssVar.margin};
color: ${cssVar.colorTextHeading};
font-size: ${cssVar.fontSizeLG};
line-height: ${cssVar.lineHeight};
`,
label: css`
display: inline-block;
margin-inline-end: ${cssVar.marginXS};
color: ${cssVar.colorTextHeading};
`,
};
});
interface DescriptionItemProps {
title: string;
content: React.ReactNode;
}
const DescriptionItem: React.FC = (props) => {
const { title, content } = props;
const { styles } = useStyles();
return (
);
};
const App: React.FC = () => {
const { styles } = useStyles();
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
(
View Profile
,
]}
>
}
title={{item.name} }
description="Progresser XTech"
/>
)}
/>
User Profile
Personal
Company
Lin} />
Contacts
github.com/ant-design/ant-design
}
/>
>
);
};
export default App;
```
### 多层抽屉
在抽屉内打开新的抽屉,用以解决多分支任务的复杂状况。
```tsx
import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [childrenDrawer, setChildrenDrawer] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
const showChildrenDrawer = () => {
setChildrenDrawer(true);
};
const onChildrenDrawerClose = () => {
setChildrenDrawer(false);
};
return (
<>
Open drawer
Two-level drawer
This is two-level drawer
>
);
};
export default App;
```
### 预设宽度
抽屉的默认宽度为 `378px`,另外还提供一个大号抽屉 `736px`,可以用 `size` 属性来设置。
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Radio, Space } from 'antd';
import type { DrawerProps } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [size, setSize] = useState();
const onClose = () => {
setOpen(false);
};
return (
<>
setSize(e.target.value)}
options={[
{ label: 'Large Size (736px)', value: 'large' },
{ label: 'Default Size (378px)', value: 'default' },
{ label: 256, value: 256 },
{ label: '500px', value: '500px' },
{ label: '50%', value: '50%' },
{ label: '20vw', value: '20vw' },
]}
/>
setOpen(true)}>
Open Drawer
Cancel
OK
}
>
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 遮罩
遮罩效果。
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Space } from 'antd';
type MaskType = 'blur' | 'dimmed' | 'none';
type DrawerConfig = {
type: MaskType;
mask: boolean | { blur: boolean };
title: string;
};
const drawerList: DrawerConfig[] = [
{ type: 'blur', mask: { blur: true }, title: 'blur' },
{ type: 'dimmed', mask: true, title: 'Dimmed mask' },
{ type: 'none', mask: false, title: 'No mask' },
];
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = (type: MaskType) => {
setOpen(type);
};
const onClose = () => {
setOpen(false);
};
return (
{drawerList.map((item) => (
{
showDrawer(item.type);
}}
>
{item.title}
Some contents...
Some contents...
Some contents...
))}
);
};
export default App;
```
### 关闭按钮位置
自定义抽屉的关闭按钮位置,放到右侧,默认为左侧。
```tsx
import React, { useState } from 'react';
import { Button, Drawer } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
};
return (
<>
Open
Some contents...
Some contents...
Take a look at the top-right corner...
>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象或者函数可以自定义 Drawer 组件的 [语义化结构](#semantic-dom) 样式。
```tsx
import React, { useState } from 'react';
import { Button, Drawer, Flex } from 'antd';
import type { DrawerProps, GetProp } from 'antd';
import { createStaticStyles } from 'antd-style';
const lineStyle: React.CSSProperties = {
lineHeight: '28px',
};
const sharedContent = (
<>
Following the Ant Design specification, we developed a React UI library antd that contains a
set of high quality components and demos for building rich, interactive user interfaces.
🌈 Enterprise-class UI designed for web applications.
📦 A set of high-quality React components out of the box.
🛡 Written in TypeScript with predictable static types.
⚙️ Whole package of design resources and development tools.
🌍 Internationalization support for dozens of languages.
🎨 Powerful theme customization in every detail.
>
);
const classNames = createStaticStyles(
({ css }): NonNullable> => ({
root: css`
border-radius: 10px;
padding: 10px;
`,
}),
);
const styles: DrawerProps['styles'] = {
mask: {
backgroundImage: `linear-gradient(to top, #18181b 0, rgba(21, 21, 22, 0.2) 100%)`,
},
};
const stylesFn: DrawerProps['styles'] = (info): GetProp => {
if (info.props.footer) {
return {
header: {
padding: 16,
},
body: {
padding: 16,
},
footer: {
padding: '16px 10px',
backgroundColor: '#fafafa',
},
};
}
};
const App: React.FC = () => {
const [drawerOpen, setDrawerOpen] = useState(false);
const [drawerFnOpen, setDrawerFnOpen] = useState(false);
const sharedProps: DrawerProps = {
classNames,
size: 500,
};
const footer: React.ReactNode = (
setDrawerFnOpen(false)}
styles={{ root: { borderColor: '#ccc', color: '#171717', backgroundColor: '#fff' } }}
>
Cancel
setDrawerOpen(true)}
>
Submit
);
return (
setDrawerOpen(true)}>Open Style Drawer
setDrawerFnOpen(true)}>
Open Function Drawer
setDrawerOpen(false)}
>
{sharedContent}
setDrawerFnOpen(false)}
>
{sharedContent}
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| afterOpenChange | 切换抽屉时动画结束后的回调 | function(open) | - | | × |
| ~~bodyStyle~~ | 抽屉内容区域样式,请使用 `styles.body` 替代 | CSSProperties | - | - | × |
| className | Drawer 容器外层 className 设置,如果需要设置最外层,请使用 rootClassName | string | - | | 5.7.0 |
| classNames | 用于自定义 Drawer 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.10.0 |
| closable | 是否显示关闭按钮。可通过 `placement` 配置其位置 | boolean \| { closeIcon?: React.ReactNode; disabled?: boolean; placement?: 'start' \| 'end' } | true | placement: 5.28.0 | 5.15.0,placement: 6.1.1 |
| ~~contentWrapperStyle~~ | 抽屉包裹层样式,请使用 `styles.wrapper` 替代 | CSSProperties | - | - | × |
| ~~destroyOnClose~~ | 关闭时销毁 Drawer 里的子元素 | boolean | false | | × |
| ~~destroyInactivePanel~~ | 关闭时销毁 Drawer 里的子元素,请使用 `destroyOnHidden` 替代 | boolean | false | - | × |
| destroyOnHidden | 关闭时销毁 Drawer 里的子元素 | boolean | false | 5.25.0 | × |
| ~~drawerStyle~~ | 抽屉面板样式,请使用 `styles.section` 替代 | CSSProperties | - | - | × |
| extra | 抽屉右上角的操作区域 | ReactNode | - | 4.17.0 | × |
| footer | 抽屉的页脚 | ReactNode | - | | × |
| ~~footerStyle~~ | 抽屉底部样式,请使用 `styles.footer` 替代 | CSSProperties | - | - | × |
| forceRender | 预渲染 Drawer 内元素 | boolean | false | | × |
| focusable | 抽屉内焦点管理的配置 | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.0 | 6.4.0 |
| getContainer | 指定 Drawer 挂载的节点,**并在容器内展现**,`false` 为挂载在当前位置 | HTMLElement \| () => HTMLElement \| Selectors \| false | body | | × |
| ~~headerStyle~~ | 抽屉头部的样式,请使用 `styles.header` 替换 | CSSProperties | - | | × |
| ~~height~~ | 高度,在 `placement` 为 `top` 或 `bottom` 时使用,请使用 `size` 替换 | string \| number | 378 | | × |
| keyboard | 是否支持键盘 esc 关闭 | boolean | true | | × |
| loading | 显示骨架屏 | boolean | false | 5.17.0 | × |
| mask | 遮罩效果 | boolean \| `{ enabled?: boolean, blur?: boolean, closable?: boolean }` | true | mask.closable: 6.3.0 | 6.0.0,mask.closable: 6.3.0 |
| ~~maskClosable~~ | 点击蒙层是否允许关闭 | boolean | true | | × |
| ~~maskStyle~~ | 抽屉遮罩样式,请使用 `styles.mask` 替代 | CSSProperties | - | - | × |
| maxSize | 可拖拽的最大尺寸(宽度或高度,取决于 `placement`) | number | - | 6.0.0 | × |
| open | Drawer 是否可见 | boolean | false | | × |
| placement | 抽屉的方向 | `top` \| `right` \| `bottom` \| `left` | `right` | | × |
| push | 用于设置多层 Drawer 的推动行为 | boolean \| { distance: string \| number } | { distance: 180 } | 4.5.0+ | × |
| resizable | 是否启用拖拽改变尺寸 | boolean \| [ResizableConfig](#resizableconfig) | - | boolean: 6.1.0 | × |
| rootStyle | 可用于设置 Drawer 最外层容器的样式,和 `style` 的区别是作用节点包括 `mask` | CSSProperties | - | | × |
| size | 预设抽屉宽度(或高度),default `378px` 和 large `736px`,或自定义数字 | 'default' \| 'large' \| number \| string | 'default' | 4.17.0, string: 6.2.0 | × |
| style | Drawer 面板的样式,如需仅配置 body 部分,请使用 `styles.body` | CSSProperties | - | | 5.7.0 |
| styles | 用于自定义 Drawer 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.10.0 |
| title | 标题 | ReactNode | - | | × |
| ~~width~~ | 宽度,请使用 `size` 替换 | string \| number | 378 | | × |
| zIndex | 设置 Drawer 的 `z-index` | number | 1000 | | × |
| onClose | 点击遮罩层或左上角叉或取消按钮的回调 | function(e) | - | | × |
| drawerRender | 自定义渲染抽屉 | (node: ReactNode) => ReactNode | - | 5.18.0 | × |
### ResizableConfig
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ------------- | ------------------------ | ---------------------- | ------ | ----- |
| onResizeStart | 开始拖拽调整大小时的回调 | () => void | - | 6.0.0 |
| onResize | 拖拽调整大小时的回调 | (size: number) => void | - | 6.0.0 |
| onResizeEnd | 结束拖拽调整大小时的回调 | () => void | - | 6.0.0 |
## Semantic DOM {#semantic-dom}
https://ant.design/components/drawer-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Drawer)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| draggerSize | 拖拽手柄大小 | number | 4 |
| footerPaddingBlock | 底部区域纵向内间距 | number | 8 |
| footerPaddingInline | 底部区域横向内间距 | number | 16 |
| zIndexPopup | 弹窗 z-index | number | 1000 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorBgMask | 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer、Image 等组件的蒙层使用的是该 token | string | |
| colorBgTextActive | 控制文本在激活状态下的背景色。 | string | |
| colorBgTextHover | 控制文本在悬停状态下的背景色。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| fontSizeLG | 大号字体大小 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## dropdown-cn
Source: https://ant.design/components/dropdown-cn.md
---
category: Components
group: 导航
title: Dropdown
subtitle: 下拉菜单
description: 向下弹出的列表。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*gTBySYX11WcAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*k619RJ_7bKEAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
当页面上的操作命令过多时,用此组件可以收纳操作元素。点击或移入触点,会出现一个下拉菜单。可在列表中进行选择,并执行相应的命令。
- 用于收罗一组命令操作。
- Select 用于选择,而 Dropdown 是命令集合。
## 代码演示 {#examples}
### 基本
最简单的下拉菜单。
```tsx
import React from 'react';
import { DownOutlined, SmileOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item (disabled)
),
icon: ,
disabled: true,
},
{
key: '3',
label: (
3rd menu item (disabled)
),
disabled: true,
},
{
key: '4',
danger: true,
label: 'a danger item',
},
];
const App: React.FC = () => (
e.preventDefault()}>
Hover me
);
export default App;
```
### 额外节点
带有快捷方式的下拉菜单。
```tsx
import React from 'react';
import { DownOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: 'My Account',
disabled: true,
},
{
type: 'divider',
},
{
key: '2',
label: 'Profile',
extra: '⌘P',
},
{
key: '3',
label: 'Billing',
extra: '⌘B',
},
{
key: '4',
label: 'Settings',
icon: ,
extra: '⌘S',
},
];
const App: React.FC = () => (
e.preventDefault()}>
Hover me
);
export default App;
```
### 弹出位置
支持 12 个弹出位置。
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item
),
},
{
key: '3',
label: (
3rd menu item
),
},
];
const App: React.FC = () => (
bottomLeft
bottom
bottomRight
topLeft
top
topRight
leftTop
left
leftBottom
rightTop
right
rightBottom
);
export default App;
```
### 箭头
可以展示一个箭头。
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item
),
},
{
key: '3',
label: (
3rd menu item
),
},
];
const App: React.FC = () => (
bottomLeft
bottom
bottomRight
topLeft
top
topRight
);
export default App;
```
### 其他元素
分割线和不可用菜单项。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: (
1st menu item
),
key: '0',
},
{
label: (
2nd menu item
),
key: '1',
},
{
type: 'divider',
},
{
label: '3rd menu item(disabled)',
key: '3',
disabled: true,
},
];
const App: React.FC = () => (
e.preventDefault()}>
Hover me
);
export default App;
```
### 箭头指向
设置 `arrow` 为 `{ pointAtCenter: true }` 后,箭头将指向目标元素的中心。
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item
),
},
{
key: '3',
label: (
3rd menu item
),
},
];
const App: React.FC = () => (
bottomLeft
bottom
bottomRight
topLeft
top
topRight
);
export default App;
```
### 触发方式
默认是移入触发菜单,可以点击触发。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: (
1st menu item
),
key: '0',
},
{
label: (
2nd menu item
),
key: '1',
},
{
type: 'divider',
},
{
label: '3rd menu item',
key: '3',
},
];
const App: React.FC = () => (
e.preventDefault()}>
Click me
);
export default App;
```
### 触发事件
点击菜单项后会触发事件,用户可以通过相应的菜单项 key 进行不同的操作。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, message, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: '1st menu item',
key: '1',
},
{
label: '2nd menu item',
key: '2',
},
{
label: '3rd menu item',
key: '3',
},
];
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const onClick: MenuProps['onClick'] = ({ key }) => {
messageApi.info(`Click on item ${key}`);
};
return (
<>
{contextHolder}
e.preventDefault()}>
Hover me, Click menu item
>
);
};
export default App;
```
### 带下拉框的按钮
左边是按钮,右边是额外的相关功能菜单。可设置 `icon` 属性来修改右边的图标。
```tsx
import React from 'react';
import { DownOutlined, EllipsisOutlined, UserOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown, message, Space, Tooltip } from 'antd';
const items: MenuProps['items'] = [
{
label: '1st menu item',
key: '1',
icon: ,
},
{
label: '2nd menu item',
key: '2',
icon: ,
},
{
label: '3rd menu item',
key: '3',
icon: ,
danger: true,
},
{
label: '4rd menu item',
key: '4',
icon: ,
danger: true,
disabled: true,
},
];
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const handleButtonClick = (e: React.MouseEvent) => {
messageApi.info('Click on left button.');
console.log('click left button', e);
};
const handleMenuClick: MenuProps['onClick'] = (e) => {
messageApi.info('Click on menu item.');
console.log('click', e);
};
const menuProps = {
items,
onClick: handleMenuClick,
};
return (
<>
{contextHolder}
Dropdown
} />
Dropdown
} />
Dropdown
} disabled />
With Tooltip
} iconPlacement="end">
Button
Danger
} danger />
>
);
};
export default App;
```
### 扩展菜单
使用 `popupRender` 对下拉菜单进行自由扩展。如果你并不需要 Menu 内容,请直接使用 Popover 组件。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Divider, Dropdown, Space, theme } from 'antd';
import type { MenuProps } from 'antd';
const { useToken } = theme;
const items: MenuProps['items'] = [
{
key: '1',
label: (
1st menu item
),
},
{
key: '2',
label: (
2nd menu item (disabled)
),
disabled: true,
},
{
key: '3',
label: (
3rd menu item (disabled)
),
disabled: true,
},
];
const App: React.FC = () => {
const { token } = useToken();
const contentStyle: React.CSSProperties = {
backgroundColor: token.colorBgElevated,
borderRadius: token.borderRadiusLG,
boxShadow: token.boxShadowSecondary,
};
const menuStyle: React.CSSProperties = {
boxShadow: 'none',
};
return (
(
{React.cloneElement(
menu as React.ReactElement<{
style: React.CSSProperties;
}>,
{ style: menuStyle },
)}
Click me!
)}
>
e.preventDefault()}>
Hover me
);
};
export default App;
```
### 多级菜单
传入的菜单里有多个层级。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
type: 'group',
label: 'Group title',
children: [
{
key: '1-1',
label: '1st menu item',
},
{
key: '1-2',
label: '2nd menu item',
},
],
},
{
key: '2',
label: 'sub menu',
children: [
{
key: '2-1',
label: '3rd menu item',
},
{
key: '2-2',
label: '4th menu item',
},
],
},
{
key: '3',
label: 'disabled sub menu',
disabled: true,
children: [
{
key: '3-1',
label: '5d menu item',
},
{
key: '3-2',
label: '6th menu item',
},
],
},
];
const App: React.FC = () => (
e.preventDefault()}>
Cascading menu
);
export default App;
```
### 菜单隐藏方式
默认是点击关闭菜单,可以关闭此功能。
```tsx
import React, { useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { DropdownProps, MenuProps } from 'antd';
import { Dropdown, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const handleMenuClick: MenuProps['onClick'] = (e) => {
if (e.key === '3') {
setOpen(false);
}
};
const handleOpenChange: DropdownProps['onOpenChange'] = (nextOpen, info) => {
if (info.source === 'trigger' || nextOpen) {
setOpen(nextOpen);
}
};
const items: MenuProps['items'] = [
{
label: 'Clicking me will not close the menu.',
key: '1',
},
{
label: 'Clicking me will not close the menu also.',
key: '2',
},
{
label: 'Clicking me will close the menu.',
key: '3',
},
];
return (
e.preventDefault()}>
Hover me
);
};
export default App;
```
### 右键菜单
默认是移入触发菜单,可以点击鼠标右键触发。弹出菜单位置会跟随右键点击位置变动。
```tsx
import React from 'react';
import type { MenuProps } from 'antd';
import { Dropdown, theme } from 'antd';
const items: MenuProps['items'] = [
{
label: '1st menu item',
key: '1',
},
{
label: '2nd menu item',
key: '2',
},
{
label: '3rd menu item',
key: '3',
},
];
const App: React.FC = () => {
const {
token: { colorBgLayout, colorTextTertiary },
} = theme.useToken();
return (
Right Click on here
);
};
export default App;
```
### 加载中状态
添加 `loading` 属性即可让按钮处于加载状态,最后两个按钮演示点击后进入加载状态。
```tsx
import React, { useState } from 'react';
import { DownOutlined, EllipsisOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Button, Dropdown, Space } from 'antd';
const items: MenuProps['items'] = [
{
label: 'Submit and continue',
key: '1',
},
];
const App: React.FC = () => {
const [loadings, setLoadings] = useState([]);
const enterLoading = (index: number) => {
setLoadings((state) => {
const newLoadings = [...state];
newLoadings[index] = true;
return newLoadings;
});
setTimeout(() => {
setLoadings((state) => {
const newLoadings = [...state];
newLoadings[index] = false;
return newLoadings;
});
}, 6000);
};
return (
Submit
} />
Submit
} />
enterLoading(0)}>
Submit
} />
enterLoading(1)}>
Submit
} />
);
};
export default App;
```
### 菜单可选选择
添加 `menu` 中的 `selectable` 属性可以开启选择能力。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Dropdown, Space, Typography } from 'antd';
const items: MenuProps['items'] = [
{
key: '1',
label: 'Item 1',
},
{
key: '2',
label: 'Item 2',
},
{
key: '3',
label: 'Item 3',
},
];
const App: React.FC = () => (
Selectable
);
export default App;
```
### 划词操作
通过 `Dropdown` 和浏览器 Selection API 组合,实现划词后的自定义操作菜单。
```tsx
import React, { useRef, useState } from 'react';
import type { MenuProps } from 'antd';
import { Dropdown, message } from 'antd';
import { createStyles } from 'antd-style';
import type { ItemType } from 'antd/es/menu/interface';
interface SelectionInfo {
text: string;
x: number;
y: number;
}
const labels: Record = {
mask: 'Mask keyword',
mark: 'Mark keyword',
search: 'Search keyword',
};
const useStyle = createStyles(({ cssVar, css }) => {
const { colorText, colorBgLayout, borderRadiusLG, paddingLG } = cssVar;
return {
wrapper: css`
padding: ${paddingLG};
user-select: text;
color: ${colorText};
background-color: ${colorBgLayout};
border-radius: ${borderRadiusLG};
`,
trigger: css`
position: fixed;
display: block;
width: 1px;
height: 1px;
margin: 0;
padding: 0;
pointer-events: none;
`,
};
});
const items = Object.entries(labels).map(([key, label]) => ({ key, label }));
const Demo: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const { styles } = useStyle();
const wrapperRef = useRef(null);
const [selection, setSelection] = useState(null);
const handleSelect = () => {
const selectionInstance = window.getSelection();
const selectedText = selectionInstance?.toString().trim();
if (!selectionInstance || !selectedText || selectionInstance.rangeCount === 0) {
setSelection(null);
return;
}
const range = selectionInstance.getRangeAt(0);
if (!wrapperRef.current?.contains(range.commonAncestorContainer)) {
setSelection(null);
return;
}
const rect = range.getBoundingClientRect();
if (!rect.width || !rect.height) {
setSelection(null);
return;
}
setSelection({
text: selectedText,
x: rect.left + rect.width / 2,
y: rect.bottom + 4,
});
};
const handleMouseUp: React.MouseEventHandler = () => {
setTimeout(handleSelect);
};
const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
if (!selection) {
return;
}
messageApi.info(`${labels[key]}: ${selection.text}`);
window.getSelection()?.removeAllRanges();
setSelection(null);
};
return (
<>
{contextHolder}
{
if (!nextOpen) {
setSelection(null);
}
}}
>
setSelection(null)}
onMouseUp={handleMouseUp}
className={styles.wrapper}
>
Select any text in this paragraph to open a Dropdown menu near the selection. This is useful
for actions such as masking sensitive words, marking entities, or searching the selected
keyword. Example data: Alice, phone 13800138000, ID 110101199001011234.
>
);
};
export default Demo;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Dropdown 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { DownOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { Button, Dropdown, Flex, Space } from 'antd';
import type { DropdownProps, GetProp, MenuProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
backgroundColor: token.colorFillAlter,
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorder}`,
borderRadius: token.borderRadius,
},
}));
const items: MenuProps['items'] = [
{
key: '1',
label: 'Profile',
},
{
key: '2',
label: 'Settings',
icon: ,
},
{
type: 'divider',
},
{
key: '3',
label: 'Logout',
icon: ,
danger: true,
},
];
const objectStyles: DropdownProps['styles'] = {
root: {
backgroundColor: '#fff',
border: '1px solid #d9d9d9',
borderRadius: '4px',
},
item: {
padding: '8px 12px',
fontSize: '14px',
},
itemTitle: {
fontWeight: '500',
},
itemIcon: {
color: '#1890ff',
marginInlineEnd: '8px',
},
itemContent: {
backgroundColor: 'transparent',
},
};
const functionStyles: DropdownProps['styles'] = (
info,
): GetProp => {
const { props } = info;
const isClick = props.trigger?.includes('click');
if (isClick) {
return {
root: {
borderColor: '#1890ff',
borderRadius: '8px',
},
};
}
return {};
};
const App: React.FC = () => {
const { styles } = useStyles();
const sharedProps: DropdownProps = {
menu: { items },
placement: 'bottomLeft',
classNames: { root: styles.root },
};
return (
Object Style
Function Style
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Dropdown
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| arrow | 下拉框箭头是否显示 | boolean \| { pointAtCenter: boolean } | false | | × |
| autoAdjustOverflow | 下拉框被遮挡时自动调整位置 | boolean | true | 5.2.0 | × |
| classNames | 用于自定义 Dropdown 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| disabled | 菜单是否禁用 | boolean | - | | × |
| ~~destroyPopupOnHide~~ | 关闭后是否销毁 Dropdown,使用 `destroyOnHidden` 替换 | boolean | false | | × |
| destroyOnHidden | 关闭后是否销毁 Dropdown | boolean | false | 5.25.0 | × |
| ~~dropdownRender~~ | 自定义下拉框内容,使用 `popupRender` 替换 | (menus: ReactNode) => ReactNode | - | 4.24.0 | × |
| popupRender | 自定义弹出框内容 | (menus: ReactNode) => ReactNode | - | 5.25.0 | × |
| getPopupContainer | 菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。[示例](https://codepen.io/afc163/pen/zEjNOy?editors=0010) | (triggerNode: HTMLElement) => HTMLElement | () => document.body | | × |
| menu | 菜单配置项 | [MenuProps](/components/menu-cn#api) | - | | × |
| ~~overlayClassName~~ | 下拉根元素的类名称, 请使用 `classNames.root` 替换 | string | - | | × |
| ~~overlayStyle~~ | 下拉根元素的样式,请使用 `styles.root` | CSSProperties | - | | × |
| placement | 菜单弹出位置:`top` `topLeft` `topRight` `bottom` `bottomLeft` `bottomRight` `left` `leftTop` `leftBottom` `right` `rightTop` `rightBottom` | string | `bottomLeft` | `left` `leftTop` `leftBottom` `right` `rightTop` `rightBottom`:6.5.0 | × |
| styles | 用于自定义 Dropdown 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom) , CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom) , CSSProperties> | - | | 6.0.0 |
| trigger | 触发下拉的行为,移动端不支持 hover | Array<`click`\|`hover`\|`contextMenu`> | \[`hover`] | | × |
| open | 菜单是否显示 | boolean | - | | × |
| onOpenChange | 菜单显示状态改变时调用,点击菜单按钮导致的消失不会触发 | (open: boolean, info: { source: 'trigger' \| 'menu' }) => void | - | `info.source`: 5.11.0 | × |
## 注意
请确保 `Dropdown` 的子元素能接受 `onMouseEnter`、`onMouseLeave`、`onFocus`、`onClick` 事件。
## Semantic DOM
https://ant.design/components/dropdown-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Dropdown)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| paddingBlock | 下拉菜单纵向内边距 | PaddingBlock \| undefined | 5 |
| zIndexPopup | 下拉菜单 z-index | number | 1050 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| boxShadowSecondary | 控制元素二级阴影样式。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| controlItemBgActive | 控制组件项在激活状态下的背景颜色。 | string | |
| controlItemBgActiveHover | 控制组件项在鼠标悬浮且激活状态下的背景颜色。 | string | |
| controlItemBgHover | 控制组件项在鼠标悬浮时的背景颜色。 | string | |
| controlPaddingHorizontal | 控制元素水平内间距。 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| motionEaseInQuint | 预设动效曲率 | string | |
| motionEaseOutCirc | 预设动效曲率 | string | |
| motionEaseOutQuint | 预设动效曲率 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
| sizePopupArrow | 组件箭头的尺寸 | number | |
## FAQ
### Dropdown 在水平方向超出屏幕时会被挤压该怎么办? {#faq-dropdown-squeezed}
你可以通过 `width: max-content` 来解决这个问题,参考 [#43025](https://github.com/ant-design/ant-design/issues/43025#issuecomment-1594394135)。
---
## empty-cn
Source: https://ant.design/components/empty-cn.md
---
category: Components
group: 数据展示
title: Empty
subtitle: 空状态
description: 空状态时的展示占位图。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ZdiZSLzEV0wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*obM7S5lIxeMAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 当目前没有数据时,用于显式的用户提示。
- 初始化场景时的引导创建流程。
## 代码演示 {#examples}
### 基本
简单的展示。
```tsx
import React from 'react';
import { Empty } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 选择图片
可以通过设置 `image` 为 `Empty.PRESENTED_IMAGE_SIMPLE` 选择另一种风格的图片。
```tsx
import React from 'react';
import { Empty } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 自定义
自定义图片链接、图片大小、描述、附属内容。
```tsx
import React from 'react';
import { Button, Empty, Typography } from 'antd';
const App: React.FC = () => (
Customize Description
}
>
Create Now
);
export default App;
```
### 全局化配置
自定义全局组件的 Empty 样式。
```tsx
import React, { useState } from 'react';
import { SmileOutlined } from '@ant-design/icons';
import {
Cascader,
ConfigProvider,
Divider,
List,
Select,
Space,
Switch,
Table,
Transfer,
TreeSelect,
} from 'antd';
const customizeRenderEmpty = () => (
);
const style: React.CSSProperties = { width: 200 };
const App: React.FC = () => {
const [customize, setCustomize] = useState(true);
return (
<>
Select
TreeSelect
Cascader
Transfer
Table
List
>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Empty 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import type { EmptyProps, GetProp } from 'antd';
import { Button, Empty, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
const emptySharedProps: EmptyProps = {
image: Empty.PRESENTED_IMAGE_SIMPLE,
children: Create Now ,
};
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 1px dashed #ccc;
padding: 16px;
`,
}));
const stylesObject: EmptyProps['styles'] = {
root: { backgroundColor: '#f5f5f5', borderRadius: '8px' },
image: { filter: 'grayscale(100%)' },
description: { color: '#1890ff', fontWeight: 'bold' },
footer: { marginTop: '16px' },
};
const stylesFn: EmptyProps['styles'] = ({ props }): GetProp => {
if (props.description) {
return {
root: { backgroundColor: '#e6f7ff', border: '1px solid #91d5ff' },
description: { color: '#1890ff', fontWeight: 'bold' },
image: { filter: 'hue-rotate(180deg)' },
};
}
return {};
};
const App: React.FC = () => {
const emptyClassNames: EmptyProps['classNames'] = {
root: classNames.root,
};
return (
);
};
export default App;
```
### 无描述
无描述展示。
```tsx
import React from 'react';
import { Empty } from 'antd';
const App: React.FC = () => ;
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
```jsx
创建
```
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 5.23.0 |
| description | 自定义描述内容 | ReactNode | - | | × |
| image | 设置显示图片,为 string 时表示自定义图片地址。 | ReactNode | `Empty.PRESENTED_IMAGE_DEFAULT` | | 5.27.0 |
| ~~imageStyle~~ | 图片样式,请使用 `styles.image` 替代 | CSSProperties | - | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 5.23.0 |
## 内置图片
- Empty.PRESENTED_IMAGE_SIMPLE
- Empty.PRESENTED_IMAGE_DEFAULT
## Semantic DOM
https://ant.design/components/empty-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginXL | 控制元素外边距,超大尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| opacityImage | 控制图片不透明度 | number | |
---
## flex-cn
Source: https://ant.design/components/flex-cn.md
---
category: Components
group: 布局
title: Flex
subtitle: 弹性布局
description: 用于对齐的弹性布局容器。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*SMzgSJZE_AwAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*8yArQ43EGccAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 适合设置元素之间的间距。
- 适合设置各种水平、垂直对齐方式。
### 与 Space 组件的区别 {#difference-with-space-component}
- Space 为内联元素提供间距,其本身会为每一个子元素添加包裹元素用于内联对齐。适用于行、列中多个子元素的等距排列。
- Flex 为块级元素提供间距,其本身不会添加包裹元素。适用于垂直或水平方向上的子元素布局,并提供了更多的灵活性和控制能力。
## 代码演示 {#examples}
### 基本布局
最简单的用法。
```tsx
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Flex, Radio } from 'antd';
const baseStyle: React.CSSProperties = {
width: '25%',
height: 54,
};
const App: React.FC = () => {
const [value, setValue] = React.useState
('horizontal');
return (
setValue(e.target.value)}>
horizontal
vertical
{Array.from({ length: 4 }).map((_, i) => (
))}
);
};
export default App;
```
### 对齐方式
设置对齐方式。
```tsx
import React from 'react';
import { Button, Flex, Segmented } from 'antd';
import type { FlexProps } from 'antd';
const boxStyle: React.CSSProperties = {
width: '100%',
height: 120,
borderRadius: 6,
border: '1px solid #40a9ff',
};
const justifyOptions = [
'flex-start',
'center',
'flex-end',
'space-between',
'space-around',
'space-evenly',
];
const alignOptions = ['flex-start', 'center', 'flex-end'];
const App: React.FC = () => {
const [justify, setJustify] = React.useState(justifyOptions[0]);
const [alignItems, setAlignItems] = React.useState(alignOptions[0]);
return (
Select justify :
Select align :
Primary
Primary
Primary
Primary
);
};
export default App;
```
### 设置间隙
使用 `gap` 设置元素之间的间距,预设了 `small`、`medium`、`large` 三种尺寸,也可以自定义间距。
```tsx
import React from 'react';
import { Button, Flex, Radio, Slider } from 'antd';
import type { FlexProps } from 'antd';
const App: React.FC = () => {
const [gapSize, setGapSize] = React.useState('small');
const [customGapSize, setCustomGapSize] = React.useState(0);
return (
setGapSize(e.target.value)}>
{['small', 'medium', 'large', 'customize'].map((size) => (
{size}
))}
{gapSize === 'customize' && }
Primary
Default
Dashed
Link
);
};
export default App;
```
### 自动换行
自动换行。
```tsx
import React from 'react';
import { Button, Flex } from 'antd';
const Demo: React.FC = () => (
{Array.from({ length: 24 }, (_, i) => (
Button
))}
);
export default Demo;
```
### 组合使用
嵌套使用,可以实现更复杂的布局。
```tsx
import React from 'react';
import { Button, Card, Flex, Typography } from 'antd';
const cardStyle: React.CSSProperties = {
width: 620,
};
const imgStyle: React.CSSProperties = {
display: 'block',
width: 273,
};
const App: React.FC = () => (
“antd is an enterprise-class UI design language and React UI library.”
Get Started
);
export default App;
```
## API
> 自 `antd@5.10.0` 版本开始提供该组件。Flex 组件默认行为在水平模式下,为向上对齐,在垂直模式下,为拉伸对齐,你可以通过属性进行调整。
通用属性参考:[通用属性](/docs/react/common-props)
| 属性 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| vertical | flex 主轴的方向是否垂直,使用 `flex-direction: column` | boolean | false | 5.10.0 | 5.10.0 |
| wrap | 设置元素单行显示还是多行显示 | [flex-wrap](https://developer.mozilla.org/zh-CN/docs/Web/CSS/flex-wrap) \| boolean | nowrap | boolean: 5.17.0 | × |
| justify | 设置元素在主轴方向上的对齐方式 | [justify-content](https://developer.mozilla.org/zh-CN/docs/Web/CSS/justify-content) | normal | | × |
| align | 设置元素在交叉轴方向上的对齐方式 | [align-items](https://developer.mozilla.org/zh-CN/docs/Web/CSS/align-items) | normal | | × |
| flex | flex CSS 简写属性 | [flex](https://developer.mozilla.org/zh-CN/docs/Web/CSS/flex) | normal | | × |
| gap | 设置网格之间的间隙 | `small` \| `medium` \| `large` \| string \| number | - | | × |
| component | 自定义元素类型 | React.ComponentType | `div` | | × |
| orientation | 主轴的方向类型 | `horizontal` \| `vertical` | `horizontal` | - | × |
## Design Token
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## float-button-cn
Source: https://ant.design/components/float-button-cn.md
---
category: Components
group: 通用
title: FloatButton
subtitle: 悬浮按钮
description: 悬浮于页面上方的按钮。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*tXAoQqyr-ioAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*hSAwR7cnabwAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 用于网站上的全局功能;
- 无论浏览到何处都可以看见的按钮。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const App: React.FC = () => console.log('onClick')} />;
export default App;
```
### 类型
通过 `type` 改变悬浮按钮的类型。
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
} type="primary" style={{ insetInlineEnd: 24 }} />
} type="default" style={{ insetInlineEnd: 94 }} />
>
);
export default App;
```
### 形状
通过 `shape` 设置不同的形状。
```tsx
import React from 'react';
import { CustomerServiceOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
}
/>
}
/>
>
);
export default App;
```
### 描述
可以通过 `content` 设置文字内容。
> 仅当 `shape` 属性为 `square` 时支持。由于空间较小,推荐使用比较精简的双数文字。
```tsx
import React from 'react';
import { FileTextOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
}
content="HELP INFO"
shape="square"
style={{ insetInlineEnd: 24 }}
/>
}
content="HELP"
shape="square"
style={{ insetInlineEnd: 164 }}
/>
>
);
export default App;
```
### 含有气泡卡片的悬浮按钮
设置 tooltip 属性,即可开启气泡卡片。
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
Documents } />
>
);
export default App;
```
### 浮动按钮组
按钮组合使用时,推荐使用 `
`,并通过设置 `shape` 属性改变悬浮按钮组的形状。悬浮按钮组的 `shape` 会覆盖内部 FloatButton 的 `shape` 属性。
```tsx
import React from 'react';
import { QuestionCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
} />
} />
} />
>
);
export default App;
```
### 菜单模式
设置 `trigger` 属性即可开启菜单模式。提供 `hover` 和 `click` 两种触发方式。
```tsx
import React from 'react';
import { CommentOutlined, CustomerServiceOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
}
>
} />
}
>
} />
>
);
export default App;
```
### 受控模式
通过 `open` 设置组件为受控模式,需要配合 `trigger` 一起使用。
```tsx
import React, { useState } from 'react';
import { CommentOutlined, CustomerServiceOutlined } from '@ant-design/icons';
import { FloatButton, Switch } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState
(true);
return (
<>
}
>
} />
}
>
} />
>
);
};
export default App;
```
### 弹出方向
自定义弹出位置,提供了四个预设值:`top`、`right`、`bottom`、`left`,默认值为 `top`。
```tsx
import React from 'react';
import {
CommentOutlined,
DownOutlined,
LeftOutlined,
RightOutlined,
UpOutlined,
} from '@ant-design/icons';
import { Flex, FloatButton } from 'antd';
const BOX_SIZE = 100;
const BUTTON_SIZE = 40;
const wrapperStyle: React.CSSProperties = {
width: '100%',
height: '100vh',
overflow: 'hidden',
position: 'relative',
};
const boxStyle: React.CSSProperties = {
width: BOX_SIZE,
height: BOX_SIZE,
position: 'relative',
};
const insetInlineEnd: React.CSSProperties['insetInlineEnd'][] = [
(BOX_SIZE - BUTTON_SIZE) / 2,
-(BUTTON_SIZE / 2),
(BOX_SIZE - BUTTON_SIZE) / 2,
BOX_SIZE - BUTTON_SIZE / 2,
];
const bottom: React.CSSProperties['bottom'][] = [
BOX_SIZE - BUTTON_SIZE / 2,
(BOX_SIZE - BUTTON_SIZE) / 2,
-BUTTON_SIZE / 2,
(BOX_SIZE - BUTTON_SIZE) / 2,
];
const icons = [
,
,
,
,
];
const App: React.FC = () => (
{(['top', 'right', 'bottom', 'left'] as const).map((placement, i) => {
const style: React.CSSProperties = {
position: 'absolute',
insetInlineEnd: insetInlineEnd[i],
bottom: bottom[i],
};
return (
} />
);
})}
);
export default App;
```
### 可拖拽
通过集成第三方库,实现拖拽功能。
```tsx
import React from 'react';
import type { DragEndEvent } from '@dnd-kit/core';
import { DndContext, PointerSensor, useDraggable, useSensor, useSensors } from '@dnd-kit/core';
import { CSS } from '@dnd-kit/utilities';
import { FloatButton } from 'antd';
interface Position {
x: number;
y: number;
}
interface DraggableButtonProps {
position: Position;
}
const DraggableButton: React.FC = (props) => {
const { position } = props;
const { attributes, isDragging, listeners, setNodeRef, transform } = useDraggable({
id: 'draggable-float-button',
});
const mergedTransform = CSS.Translate.toString({
x: position.x + (transform?.x ?? 0),
y: position.y + (transform?.y ?? 0),
scaleX: transform?.scaleX ?? 1,
scaleY: transform?.scaleY ?? 1,
});
return (
);
};
const Demo: React.FC = () => {
const [position, setPosition] = React.useState({ x: 0, y: 0 });
const sensor = useSensor(PointerSensor, {
activationConstraint: {
distance: 10,
},
});
const sensors = useSensors(sensor);
const onDragEnd = (event: DragEndEvent) => {
const { delta } = event;
setPosition(({ x, y }) => ({ x: x + delta.x, y: y + delta.y }));
};
return (
);
};
export default Demo;
```
### 回到顶部
返回页面顶部的操作按钮。
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const Demo: React.FC = () => {
return (
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
);
};
export default Demo;
```
### 滚动进度
通过 `showProgress` 在回到顶部按钮边缘展示当前滚动进度。
```tsx
import React from 'react';
import { FloatButton } from 'antd';
const sharedProps: React.ComponentProps = {
showProgress: true,
visibilityHeight: 0,
};
const Demo: React.FC = () => {
return (
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
);
};
export default Demo;
```
### 徽标数
右上角附带圆形徽标数字的悬浮按钮。
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
const App: React.FC = () => (
<>
custom badge color }
badge={{ count: 5, color: 'blue' }}
/>
} />
>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 FloatButton 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { FloatButton } from 'antd';
import type { FloatButtonProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `${token.lineWidth}px ${token.lineType} ${token.colorBorder}`,
borderRadius: token.borderRadius,
padding: `${token.paddingXS}px ${token.padding}px`,
height: 'auto',
},
content: {
color: token.colorText,
},
}));
const stylesObject: FloatButtonProps['styles'] = {
root: {
boxShadow: '0 1px 2px 0 rgba(0,0,0,0.05)',
},
};
const stylesFn: FloatButtonProps['styles'] = (
info,
): GetProp => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
};
}
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
custom style class}
/>
}
/>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> 自 `antd@5.0.0` 版本开始提供该组件。
### 共同的 API
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| icon | 自定义图标 | ReactNode | - | | FloatButton: ×,BackTop: 5.27.0 |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| content | 文字及其它内容 | ReactNode | - | | × |
| ~~description~~ | 请使用 `content` 代替 | ReactNode | - | | × |
| tooltip | 气泡卡片的内容 | ReactNode \| [TooltipProps](/components/tooltip-cn#api) | - | TooltipProps: 5.25.0 | × |
| type | 设置按钮类型 | `default` \| `primary` | `default` | | × |
| shape | 设置按钮形状 | `circle` \| `square` | `circle` | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| onClick | 点击按钮时的回调 | (event) => void | - | | × |
| href | 点击跳转的地址,指定此属性 button 的行为和 a 链接一致 | string | - | | × |
| target | 相当于 a 标签的 target 属性,href 存在时生效 | string | - | | × |
| htmlType | 设置 `button` 原生的 `type` 值,可选值请参考 [HTML 标准](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/button#type) | `submit` \| `reset` \| `button` | `button` | 5.21.0 | × |
| badge | 带徽标数字的悬浮按钮(不支持 `status` 以及相关属性) | [BadgeProps](/components/badge-cn#api) | - | 5.4.0 | × |
| disabled | 按钮是否禁用 | boolean | - | 6.4.0 | × |
### FloatButton.Group
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| shape | 设置包含的 FloatButton 按钮形状 | `circle` \| `square` | `circle` | | × |
| trigger | 触发方式(有触发方式为菜单模式) | `click` \| `hover` | - | | × |
| open | 受控展开,需配合 trigger 一起使用 | boolean | - | | × |
| closeIcon | 自定义关闭按钮 | React.ReactNode | ` ` | | 5.16.0 |
| placement | 自定义菜单弹出位置 | `top` \| `left` \| `right` \| `bottom` | `top` | 5.21.0 | × |
| onOpenChange | 展开收起时的回调,需配合 trigger 一起使用 | (open: boolean) => void | - | | × |
| onClick | 点击按钮时的回调(仅在菜单模式中有效) | (event) => void | - | 5.3.0 | × |
### FloatButton.BackTop
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| duration | 回到顶部所需时间(ms);开启“减弱动态效果”(`prefers-reduced-motion: reduce`)时不生效 | number | 450 | |
| showProgress | 在 BackTop 按钮边缘展示当前滚动进度环 | boolean | false | 6.6.0 |
| target | 设置需要监听其滚动事件的元素 | () => HTMLElement | () => window | |
| visibilityHeight | 滚动高度达到此参数值才出现 BackTop | number | 400 | |
| onClick | 点击按钮的回调函数 | () => void | - | |
## Semantic DOM
### FloatButton
https://ant.design/components/float-button-cn/semantic.md
### FloatButton.Group
https://ant.design/components/float-button-cn/semantic_group.md
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| boxShadowSecondary | 控制元素二级阴影样式。 | string | |
| colorBorderSecondary | 比默认使用的边框色要浅一级,此颜色和 colorSplit 的颜色一致。使用的是实色。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| marginLG | 控制元素外边距,大尺寸。 | number | |
| marginXXL | 控制元素外边距,最大尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| padding | 控制元素的内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
| zIndexPopupBase | 浮层类组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 FloatButton、 Affix、Modal 等 | number | |
---
## form-cn
Source: https://ant.design/components/form-cn.md
---
category: Components
group: 数据录入
title: Form
subtitle: 表单
description: 高性能表单控件,自带数据域管理。包含数据录入、校验以及对应样式。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-lcdS5Qm1bsAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ylFATY6w-ygAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 用于创建一个实体或收集信息。
- 需要对输入的数据类型进行校验时。
## 代码演示 {#examples}
### 基本使用
基本的表单数据域控制展示,包含布局、初始化、验证、提交。
```tsx
import React from 'react';
import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input } from 'antd';
type FieldType = {
username?: string;
password?: string;
remember?: string;
};
const onFinish: FormProps['onFinish'] = (values) => {
console.log('Success:', values);
};
const onFinishFailed: FormProps['onFinishFailed'] = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const App: React.FC = () => (
label="Username"
name="username"
rules={[{ required: true, message: 'Please input your username!' }]}
>
label="Password"
name="password"
rules={[{ required: true, message: 'Please input your password!' }]}
>
name="remember" valuePropName="checked" label={null}>
Remember me
Submit
);
export default App;
```
### 表单方法调用
通过 `Form.useForm` 对表单数据域进行交互。
> 注意 `useForm` 是 [React Hooks](https://zh-hans.react.dev/reference/react/hooks) 的实现,只能用于函数组件。如果是在 Class Component 下,你也可以通过 `ref` 获取数据域:https://codesandbox.io/p/sandbox/ngtjtm
```tsx
import React from 'react';
import { Button, Form, Input, Select, Space } from 'antd';
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
const App: React.FC = () => {
const [form] = Form.useForm();
const onGenderChange = (value: string) => {
switch (value) {
case 'male':
form.setFieldsValue({ note: 'Hi, man!' });
break;
case 'female':
form.setFieldsValue({ note: 'Hi, lady!' });
break;
case 'other':
form.setFieldsValue({ note: 'Hi there!' });
break;
default:
}
};
const onFinish = (values: any) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({ note: 'Hello world!', gender: 'male' });
};
return (
prevValues.gender !== currentValues.gender}
>
{({ getFieldValue }) =>
getFieldValue('gender') === 'other' ? (
) : null
}
Submit
Reset
Fill form
);
};
export default App;
```
### 表单布局
表单有三种布局。
```tsx
import React, { useState } from 'react';
import { Button, Form, Input, Radio } from 'antd';
import type { FormProps } from 'antd';
type LayoutType = Parameters[0]['layout'];
const App: React.FC = () => {
const [form] = Form.useForm();
const [formLayout, setFormLayout] = useState('horizontal');
const onFormLayoutChange: FormProps['onValuesChange'] = ({ layout }) => {
setFormLayout(layout);
};
return (
Horizontal
Vertical
Inline
Submit
);
};
export default App;
```
### 表单混合布局
在 `Form.Item` 上单独定义 `layout`,可以做到一个表单多种布局。
```tsx
import React from 'react';
import { Divider, Form, Input } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 表单禁用
设置表单组件禁用,仅对 antd 组件有效。
```tsx
import React, { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
Button,
Cascader,
Checkbox,
ColorPicker,
DatePicker,
Form,
Input,
InputNumber,
Mentions,
Radio,
Rate,
Select,
Slider,
Switch,
Transfer,
Tree,
TreeSelect,
Upload,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const normFile = (e: any) => {
if (Array.isArray(e)) {
return e;
}
return e?.fileList;
};
const FormDisabledDemo: React.FC = () => {
const [componentDisabled, setComponentDisabled] = useState(true);
return (
<>
setComponentDisabled(e.target.checked)}
>
Form disabled
Checkbox
Apple
Pear
Upload
Button
({
key: i.toString(),
title: `Content ${i + 1}`,
description: `Description of content ${i + 1}`,
}))}
targetKeys={['1', '3', '5']}
render={(item) => item.title}
/>
>
);
};
export default () => ;
```
### 表单变体
改变表单内所有组件的变体,可选 `outlined` `filled` `borderless` `underlined` 四种形态。
```tsx
import React from 'react';
import {
Button,
Cascader,
DatePicker,
Form,
Input,
InputNumber,
Mentions,
Segmented,
Select,
TreeSelect,
} from 'antd';
const { RangePicker } = DatePicker;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const App: React.FC = () => {
const [form] = Form.useForm();
const variant = Form.useWatch('variant', form);
return (
Submit
);
};
export default App;
```
### 必选样式
通过 `requiredMark` 切换必选与可选样式。
```tsx
import React, { useState } from 'react';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Button, Form, Input, Radio, Tag } from 'antd';
import type { FormProps } from 'antd';
type RequiredMark = boolean | 'optional' | 'customize';
const customizeRequiredMark = (label: React.ReactNode, { required }: { required: boolean }) => (
<>
{required ? Required : optional }
{label}
>
);
const App: React.FC = () => {
const [form] = Form.useForm();
const [requiredMark, setRequiredMark] = useState('optional');
const onRequiredTypeChange: FormProps['onValuesChange'] = ({ requiredMarkValue }) => {
setRequiredMark(requiredMarkValue);
};
return (
Default
Optional
Hidden
Customize
}}
>
Submit
);
};
export default App;
```
### 表单尺寸
设置表单组件尺寸,仅对 antd 组件有效。
```tsx
import React, { useState } from 'react';
import {
Button,
Cascader,
DatePicker,
Form,
Input,
InputNumber,
Radio,
Select,
Switch,
TreeSelect,
} from 'antd';
import type { FormProps } from 'antd';
type SizeType = Parameters[0]['size'];
const App: React.FC = () => {
const [componentSize, setComponentSize] = useState('medium');
const onFormLayoutChange: FormProps['onValuesChange'] = ({ size }) => {
setComponentSize(size);
};
return (
Small
Medium
Large
Button
);
};
export default App;
```
### 表单标签可换行
使用 `labelWrap` 可以开启 `label` 换行。
```tsx
import React from 'react';
import { Button, Form, Input } from 'antd';
const App: React.FC = () => (
Submit
);
export default App;
```
### 非阻塞校验
`rule` 添加 `warningOnly` 后校验不再阻塞表单提交。
```tsx
import React from 'react';
import { Button, Form, Input, message, Space } from 'antd';
const App: React.FC = () => {
const [messageApi, contextHolder] = message.useMessage();
const [form] = Form.useForm();
const onFinish = () => {
messageApi.success('Submit success!');
};
const onFinishFailed = () => {
messageApi.error('Submit failed!');
};
const onFill = () => {
form.setFieldsValue({
url: 'https://taobao.com/',
});
};
return (
<>
{contextHolder}
Submit
Fill
>
);
};
export default App;
```
### 字段监听 Hooks
`useWatch` 允许你监听字段变化,同时仅当该字段变化时重新渲染。API 文档请[查阅此处](#formusewatch)。
```tsx
import React from 'react';
import { Form, Input, InputNumber, Typography } from 'antd';
const Demo: React.FC = () => {
const [form] = Form.useForm<{ name: string; age: number }>();
const nameValue = Form.useWatch('name', form);
// The selector is static and does not support closures.
const customValue = Form.useWatch((values) => `name: ${values.name || ''}`, form);
return (
<>
Name Value: {nameValue}
Custom Value: {customValue}
>
);
};
export default Demo;
```
### 校验时机
对于有异步校验的场景,过于频繁的校验会导致后端压力。可以通过 `validateTrigger` 改变校验时机,或者 `validateDebounce` 改变校验频率,或者 `validateFirst` 设置校验短路。
```tsx
import React from 'react';
import { Alert, Form, Input } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 仅校验
通过 `validateFields` 的 `validateOnly` 可以动态调整提交按钮的 `disabled` 状态。
```tsx
import React from 'react';
import type { FormInstance } from 'antd';
import { Button, Form, Input, Space } from 'antd';
interface SubmitButtonProps {
form: FormInstance;
}
const SubmitButton: React.FC> = ({ form, children }) => {
const [submittable, setSubmittable] = React.useState(false);
// Watch all values
const values = Form.useWatch([], form);
React.useEffect(() => {
form
.validateFields({ validateOnly: true })
.then(() => setSubmittable(true))
.catch(() => setSubmittable(false));
}, [form, values]);
return (
{children}
);
};
const App: React.FC = () => {
const [form] = Form.useForm();
return (
Submit
Reset
);
};
export default App;
```
### 字段路径前缀
在某些场景,你希望统一设置一些字段的前缀。你可以通过 HOC 实现该效果。
```tsx
import React from 'react';
import { Button, Form, Input } from 'antd';
import type { FormItemProps } from 'antd';
const MyFormItemContext = React.createContext<(string | number)[]>([]);
interface MyFormItemGroupProps {
prefix: string | number | (string | number)[];
}
function toArr(str: string | number | (string | number)[]): (string | number)[] {
return Array.isArray(str) ? str : [str];
}
const MyFormItemGroup: React.FC> = ({
prefix,
children,
}) => {
const prefixPath = React.useContext(MyFormItemContext);
const concatPath = React.useMemo(() => [...prefixPath, ...toArr(prefix)], [prefixPath, prefix]);
return {children} ;
};
const MyFormItem = ({ name, ...props }: FormItemProps) => {
const prefixPath = React.useContext(MyFormItemContext);
const concatName = name !== undefined ? [...prefixPath, ...toArr(name)] : undefined;
return ;
};
const App: React.FC = () => {
const onFinish = (value: object) => {
console.log(value);
};
return (
);
};
export default App;
```
### 动态增减表单项
动态增加、减少表单项。`add` 方法参数可用于设置初始值。
```tsx
import React from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css, cssVar } = props;
return {
dynamicDeleteButton: css`
position: relative;
top: ${cssVar.marginXXS};
margin: 0 ${cssVar.marginXS};
color: #999;
font-size: 24px;
cursor: pointer;
transition: all ${cssVar.motionDurationSlow} ease;
&:hover {
color: #777;
}
&[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
`,
};
});
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
const App: React.FC = () => {
const { styles } = useStyles();
const onFinish = (values: any) => {
console.log('Received values of form:', values);
};
return (
{
if (!names || names.length < 2) {
return Promise.reject(new Error('At least 2 passengers'));
}
},
},
]}
>
{(fields, { add, remove }, { errors }) => (
<>
{fields.map((field, index) => (
{fields.length > 1 ? (
remove(field.name)}
/>
) : null}
))}
add()}
style={{ width: '60%' }}
icon={ }
>
Add field
{
add('The head item', 0);
}}
style={{ width: '60%', marginTop: '20px' }}
icon={ }
>
Add field at head
>
)}
Submit
);
};
export default App;
```
### 动态增减嵌套字段
嵌套表单字段需要对 `field` 进行拓展,将 `field.name` 应用于控制字段。
```tsx
import React from 'react';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Space } from 'antd';
const onFinish = (values: any) => {
console.log('Received values of form:', values);
};
const App: React.FC = () => (
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, ...restField }) => (
remove(name)} />
))}
add()} block icon={ }>
Add field
>
)}
Submit
);
export default App;
```
### 拖拽排序
结合 [dnd-kit](https://github.com/clauderic/dnd-kit) 与 `Form.List` 提供的 `move` 操作,实现动态表单项的拖拽排序。拖拽以每个字段稳定的 `key` 作为标识,结束拖拽时调用 `move(from, to)` 调整顺序,表单数据会随之同步。
```tsx
import React, { useContext, useMemo } from 'react';
import { HolderOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { DragEndEvent, DraggableAttributes, DraggableSyntheticListeners } from '@dnd-kit/core';
import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import { SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Button, Form, Input, Space } from 'antd';
const onFinish = (values: any) => {
console.log('Received values of form:', values);
};
interface RowContextProps {
setActivatorNodeRef?: (element: HTMLElement | null) => void;
listeners?: DraggableSyntheticListeners;
attributes?: DraggableAttributes;
}
const RowContext = React.createContext({});
const DragHandle: React.FC = () => {
const { setActivatorNodeRef, listeners, attributes } = useContext(RowContext);
return (
}
style={{ cursor: 'move' }}
ref={setActivatorNodeRef}
{...attributes}
{...listeners}
/>
);
};
interface SortableItemProps {
id: number;
children?: React.ReactNode;
}
const SortableItem: React.FC = ({ id, children }) => {
const {
setNodeRef,
setActivatorNodeRef,
attributes,
listeners,
transform,
transition,
isDragging,
} = useSortable({ id });
const style: React.CSSProperties = {
transform: CSS.Translate.toString(transform),
transition,
...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
};
const contextValue = useMemo(
() => ({ setActivatorNodeRef, listeners, attributes }),
[setActivatorNodeRef, listeners, attributes],
);
return (
{children}
);
};
const App: React.FC = () => {
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 1 } }));
return (
{(fields, { add, remove, move }) => {
const onDragEnd = ({ active, over }: DragEndEvent) => {
if (over && active.id !== over.id) {
const activeIndex = fields.findIndex((field) => field.key === active.id);
const overIndex = fields.findIndex((field) => field.key === over.id);
if (activeIndex !== -1 && overIndex !== -1) {
move(activeIndex, overIndex);
}
}
};
return (
field.key)}
strategy={verticalListSortingStrategy}
>
{fields.map(({ key, name, ...restField }) => (
remove(name)} />
))}
add()} block icon={ }>
Add field
);
}}
Submit
);
};
export default App;
```
### 复杂的动态增减表单项
多个 Form.List 嵌套的使用场景。
```tsx
import React from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { Button, Card, Form, Input, Space, Typography } from 'antd';
const App: React.FC = () => {
const [form] = Form.useForm();
return (
{(fields, { add, remove }) => (
)}
{() => (
{JSON.stringify(form.getFieldsValue(), null, 2)}
)}
);
};
export default App;
```
### 嵌套结构与校验信息
`name` 属性支持嵌套数据结构。通过 `validateMessages` 或 `message` 自定义校验信息模板,模板内容可参考[此处](https://github.com/react-component/field-form/blob/master/src/utils/messages.ts)。
```tsx
import React from 'react';
import { Button, Form, Input, InputNumber } from 'antd';
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const validateMessages = {
required: '${label} is required!',
types: {
email: '${label} is not a valid email!',
number: '${label} is not a valid number!',
},
number: {
range: '${label} must be between ${min} and ${max}',
},
};
const onFinish = (values: any) => {
console.log(values);
};
const App: React.FC = () => (
Submit
);
export default App;
```
### 复杂一点的控件
这里演示 `Form.Item` 内有多个元素的使用方式。` ` 只会对它的直接子元素绑定表单功能,例如直接包裹了 Input/Select。如果控件前后还有一些文案或样式装点,或者一个表单项内有多个控件,你可以使用内嵌的 `Form.Item` 完成。你可以给 `Form.Item` 自定义 `style` 进行内联布局,或者添加 `noStyle` 作为纯粹的无样式绑定组件(类似 3.x 中的 `getFieldDecorator`)。
```diff
-
-
-
+
+ // 直接包裹才会绑定表单
+ description
+
```
这里展示了三种典型场景:
- `Username`:输入框后面有描述文案或其他组件,在 `Form.Item` 内使用 ` ` 去绑定对应子控件。
- `Address`:有两个控件,在 `Form.Item` 内使用两个 ` ` 分别绑定对应控件。
- `BirthDate`:有两个内联控件,错误信息展示各自控件下,使用两个 ` ` 分别绑定对应控件,并修改 `style` 使其内联布局。
> 注意,在 label 对应的 Form.Item 上不要在指定 `name` 属性,这个 Item 只作为布局作用。
更复杂的封装复用方式可以参考下面的 `自定义表单控件` 演示。
```tsx
import React from 'react';
import { Button, Form, Input, Select, Space, Tooltip, Typography } from 'antd';
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const App: React.FC = () => (
Need Help?
Submit
);
export default App;
```
### 自定义表单控件
自定义或第三方的表单控件,也可以与 Form 组件一起使用。只要该组件遵循以下的约定:
> - 提供受控属性 `value` 或其它与 [`valuePropName`](#formitem) 的值同名的属性。
> - 提供 `onChange` 事件或 [`trigger`](#formitem) 的值同名的事件。
> - 转发 ref 或者传递 id 属性到 dom 以支持 `scrollToField` 方法。
```tsx
import React, { useState } from 'react';
import { Button, Form, Input, Select } from 'antd';
type Currency = 'rmb' | 'dollar';
interface PriceValue {
number?: number;
currency?: Currency;
}
interface PriceInputProps {
id?: string;
value?: PriceValue;
onChange?: (value: PriceValue) => void;
}
const PriceInput: React.FC = (props) => {
const { id, value = {}, onChange } = props;
const [number, setNumber] = useState(0);
const [currency, setCurrency] = useState('rmb');
const triggerChange = (changedValue: { number?: number; currency?: Currency }) => {
onChange?.({ number, currency, ...value, ...changedValue });
};
const onNumberChange = (e: React.ChangeEvent) => {
const newNumber = Number.parseInt(e.target.value || '0', 10);
if (Number.isNaN(number)) {
return;
}
if (!('number' in value)) {
setNumber(newNumber);
}
triggerChange({ number: newNumber });
};
const onCurrencyChange = (newCurrency: Currency) => {
if (!('currency' in value)) {
setCurrency(newCurrency);
}
triggerChange({ currency: newCurrency });
};
return (
);
};
const App: React.FC = () => {
const onFinish = (values: any) => {
console.log('Received values from form: ', values);
};
const checkPrice = (_: any, value: { number: number }) => {
if (value.number > 0) {
return Promise.resolve();
}
return Promise.reject(new Error('Price must be greater than zero!'));
};
return (
Submit
);
};
export default App;
```
### 表单数据存储于上层组件
通过 `onFieldsChange` 和 `fields`,可以把表单的数据存储到上层组件或者 [Redux](https://github.com/reactjs/redux)、[dva](https://github.com/dvajs/dva) 中,更多可参考 [rc-field-form 示例](https://rc-field-form.react-component.now.sh/?selectedKind=rc-field-form&selectedStory=StateForm-redux&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Factions%2Factions-panel)。
`onFieldsChange` 返回扁平的 `FieldData[]`。当字段名为数组路径时,`FieldData.name` 会保留该路径,而不是转换为嵌套对象,便于在外部状态中逐项处理字段。
**注意:** 将表单数据存储于外部容器[并非好的实践](https://github.com/reduxjs/redux/issues/1287#issuecomment-175351978),如无必要请避免使用。
```tsx
import React, { useState } from 'react';
import { Form, Input, Typography } from 'antd';
const { Paragraph } = Typography;
interface FieldData {
name: string | number | (string | number)[];
value?: unknown;
touched?: boolean;
validating?: boolean;
errors?: string[];
}
interface CustomizedFormProps {
onChange: (fields: FieldData[]) => void;
fields: FieldData[];
}
const CustomizedForm: React.FC = ({ onChange, fields }) => (
);
const App: React.FC = () => {
const [fields, setFields] = useState([
{ name: ['username'], value: 'Ant Design' },
{ name: ['profile', 'email'], value: 'antd@example.com' },
]);
return (
<>
{
setFields(newFields);
}}
/>
{JSON.stringify(fields, null, 2)}
>
);
};
export default App;
```
### 多表单联动
通过 `Form.Provider` 在表单间处理数据。本例子中,Modal 的确认按钮在 Form 之外,通过 `form.submit` 方法调用表单提交功能。反之,则推荐使用 ` ` 调用 web 原生提交逻辑。
```tsx
import React, { useEffect, useRef, useState } from 'react';
import { SmileOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Button, Flex, Form, Input, InputNumber, Modal, Space, Typography } from 'antd';
import type { GetRef } from 'antd';
type FormInstance = GetRef;
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
interface UserType {
name: string;
age: string;
}
interface ModalFormProps {
open: boolean;
onCancel: () => void;
}
// reset form fields when modal is form, closed
const useResetFormOnCloseModal = ({ form, open }: { form: FormInstance; open: boolean }) => {
const prevOpenRef = useRef(null);
useEffect(() => {
prevOpenRef.current = open;
}, [open]);
const prevOpen = prevOpenRef.current;
useEffect(() => {
if (!open && prevOpen) {
form.resetFields();
}
}, [form, prevOpen, open]);
};
const ModalForm: React.FC = ({ open, onCancel }) => {
const [form] = Form.useForm();
useResetFormOnCloseModal({
form,
open,
});
const onOk = () => {
form.submit();
};
return (
);
};
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showUserModal = () => {
setOpen(true);
};
const hideUserModal = () => {
setOpen(false);
};
const onFinish = (values: any) => {
console.log('Finish:', values);
};
return (
{
if (name === 'userForm') {
const { basicForm } = forms;
const users = basicForm.getFieldValue('users') || [];
basicForm.setFieldsValue({ users: [...users, values] });
setOpen(false);
}
}}
>
{/* Create a hidden field to make Form instance record this */}
prevValues.users !== curValues.users}
>
{({ getFieldValue }) => {
const users: UserType[] = getFieldValue('users') || [];
return users.length ? (
{users.map((user) => (
} />
{`${user.name} - ${user.age}`}
))}
) : (
( No user yet. )
);
}}
Submit
Add User
);
};
export default App;
```
### 内联登录栏
内联登录栏,常用在顶部导航栏中。
```tsx
import React, { useEffect, useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
const App: React.FC = () => {
const [form] = Form.useForm();
const [clientReady, setClientReady] = useState(false);
// To disable submit button at the beginning.
useEffect(() => {
setClientReady(true);
}, []);
const onFinish = (values: any) => {
console.log('Finish:', values);
};
return (
} placeholder="Username" />
} type="password" placeholder="Password" />
{() => (
errors.length)
}
>
Log in
)}
);
};
export default App;
```
### 登录框
普通的登录框,可以容纳更多的元素。
> 🛎️ 想要 3 分钟实现登录表单?试试 [Pro Components](https://procomponents.ant.design/components/login-form)!
```tsx
import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Flex, Form, Input } from 'antd';
const App: React.FC = () => {
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
return (
} placeholder="Username" />
} type="password" placeholder="Password" />
Remember me
Forgot password
Log in
or Register now!
);
};
export default App;
```
### 注册新用户
用户填写必须的信息以注册新用户。
```tsx
import React, { useState } from 'react';
import type { CascaderProps, FormItemProps, FormProps } from 'antd';
import {
AutoComplete,
Button,
Cascader,
Checkbox,
Col,
Form,
Input,
InputNumber,
Row,
Select,
Space,
} from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
interface FormCascaderOption {
value: string;
label: string;
children?: FormCascaderOption[];
}
const residences: CascaderProps['options'] = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
const formItemLayout: FormProps = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const tailFormItemLayout: FormItemProps = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
interface PhoneValue {
prefix?: string;
phone?: string;
}
interface PhoneInputProps {
id?: string;
value?: PhoneValue;
onChange?: (value: PhoneValue) => void;
}
const PhoneInput: React.FC = ({ id, value = {}, onChange }) => {
const [prefix, setPrefix] = useState('86');
const [phone, setPhone] = useState('');
const triggerChange = (changedValue: PhoneValue) => {
onChange?.({ ...value, ...changedValue });
};
const onPrefixChange = (newPrefix: string) => {
if (!('prefix' in value)) {
setPrefix(newPrefix);
}
triggerChange({ prefix: newPrefix });
};
const onPhoneChange = (e: React.ChangeEvent) => {
const newPhone = e.target.value;
if (!('phone' in value)) {
setPhone(newPhone);
}
triggerChange({ phone: newPhone });
};
return (
);
};
interface DonationValue {
amount?: number;
currency?: string;
}
interface DonationInputProps {
id?: string;
value?: DonationValue;
onChange?: (value: DonationValue) => void;
}
const DonationInput: React.FC = ({ id, value = {}, onChange }) => {
const [amount, setAmount] = useState();
const [currency, setCurrency] = useState('USD');
const triggerChange = (changedValue: DonationValue) => {
onChange?.({ ...value, ...changedValue });
};
const onAmountChange = (newAmount: number | null) => {
if (!('amount' in value)) {
setAmount(newAmount ?? undefined);
}
triggerChange({ amount: newAmount ?? undefined });
};
const onCurrencyChange = (newCurrency: string) => {
if (!('currency' in value)) {
setCurrency(newCurrency);
}
triggerChange({ currency: newCurrency });
};
return (
);
};
const App: React.FC = () => {
const [form] = Form.useForm();
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const [autoCompleteResult, setAutoCompleteResult] = useState([]);
const onWebsiteChange = (value: string) => {
setAutoCompleteResult(
value ? ['.com', '.org', '.net'].map((domain) => `${value}${domain}`) : [],
);
};
const websiteOptions = autoCompleteResult.map((website) => ({
label: website,
value: website,
}));
return (
({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('The new password that you entered do not match!'));
},
}),
]}
>
Get captcha
value ? Promise.resolve() : Promise.reject(new Error('Should accept agreement')),
},
]}
{...tailFormItemLayout}
>
I have read the agreement
Register
);
};
export default App;
```
### 高级搜索
三列栅格式的表单排列方式,常用于数据表格的高级搜索。
有部分定制的样式代码,由于输入标签长度不确定,需要根据具体情况自行调整。
> 🛎️ 想要 3 分钟实现? 试试 ProForm 的[查询表单](https://procomponents.ant.design/components/form#%E6%9F%A5%E8%AF%A2%E7%AD%9B%E9%80%89)!
```tsx
import React, { useState } from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Select, Space, theme } from 'antd';
const AdvancedSearchForm = () => {
const { token } = theme.useToken();
const [form] = Form.useForm();
const [expand, setExpand] = useState(false);
const formStyle: React.CSSProperties = {
maxWidth: 'none',
background: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
padding: 24,
};
const getFields = () => {
const count = expand ? 10 : 6;
const children: React.ReactNode[] = [];
for (let i = 0; i < count; i++) {
children.push(
{i % 3 !== 1 ? (
) : (
)}
,
);
}
return children;
};
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
return (
);
};
const App: React.FC = () => {
const { token } = theme.useToken();
const listStyle: React.CSSProperties = {
lineHeight: '200px',
textAlign: 'center',
background: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
marginTop: 16,
};
return (
<>
Search Result List
>
);
};
export default App;
```
### 弹出层中的新建表单
当用户访问一个展示了某个列表的页面,想新建一项但又不想跳转页面时,可以用 Modal 弹出一个表单,用户填写必要信息后创建新的项。
> 🛎️ 想要 3 分钟实现?试试 ProForm 的 [Modal 表单](https://procomponents.ant.design/components/form#modal-%E8%A1%A8%E5%8D%95)!
```tsx
import React, { useState } from 'react';
import { Button, Form, Input, Modal, Radio } from 'antd';
interface Values {
title?: string;
description?: string;
modifier?: string;
}
const App: React.FC = () => {
const [form] = Form.useForm();
const [formValues, setFormValues] = useState();
const [open, setOpen] = useState(false);
const onCreate = (values: Values) => {
console.log('Received values of form: ', values);
setFormValues(values);
setOpen(false);
};
return (
<>
setOpen(true)}>
New Collection
{JSON.stringify(formValues, null, 2)}
setOpen(false)}
destroyOnHidden
modalRender={(dom) => (
)}
>
Public
Private
>
);
};
export default App;
```
### 时间类控件
时间类组件的 `value` 类型为 `dayjs` 对象,所以在提交服务器前需要预处理。
```tsx
import React from 'react';
import { Button, DatePicker, Form, TimePicker } from 'antd';
const { RangePicker } = DatePicker;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const config = {
rules: [{ type: 'object' as const, required: true, message: 'Please select time!' }],
};
const rangeConfig = {
rules: [{ type: 'array' as const, required: true, message: 'Please select time!' }],
};
const onFinish = (fieldsValue: any) => {
// Should format date value before submit.
const rangeValue = fieldsValue['range-picker'];
const rangeTimeValue = fieldsValue['range-time-picker'];
const values = {
...fieldsValue,
'date-picker': fieldsValue['date-picker'].format('YYYY-MM-DD'),
'date-time-picker': fieldsValue['date-time-picker'].format('YYYY-MM-DD HH:mm:ss'),
'month-picker': fieldsValue['month-picker'].format('YYYY-MM'),
'range-picker': [rangeValue[0].format('YYYY-MM-DD'), rangeValue[1].format('YYYY-MM-DD')],
'range-time-picker': [
rangeTimeValue[0].format('YYYY-MM-DD HH:mm:ss'),
rangeTimeValue[1].format('YYYY-MM-DD HH:mm:ss'),
],
'time-picker': fieldsValue['time-picker'].format('HH:mm:ss'),
};
console.log('Received values of form: ', values);
};
const App: React.FC = () => (
Submit
);
export default App;
```
### 自行处理表单数据
`Form` 具有自动收集数据并校验的功能,但如果您不需要这个功能,或者默认的行为无法满足业务需求,可以选择自行处理数据。
```tsx
import React, { useState } from 'react';
import type { InputNumberProps } from 'antd';
import { Form, InputNumber } from 'antd';
type ValidateStatus = Parameters[0]['validateStatus'];
const validatePrimeNumber = (
number: number,
): {
validateStatus: ValidateStatus;
errorMsg: string | null;
} => {
if (number === 11) {
return {
validateStatus: 'success',
errorMsg: null,
};
}
return {
validateStatus: 'error',
errorMsg: 'The prime between 8 and 12 is 11!',
};
};
const formItemLayout = {
labelCol: { span: 7 },
wrapperCol: { span: 12 },
};
const tips =
'A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.';
const App: React.FC = () => {
const [number, setNumber] = useState<{
value: number;
validateStatus?: ValidateStatus;
errorMsg?: string | null;
}>({ value: 11 });
const onNumberChange: InputNumberProps['onChange'] = (value) => {
setNumber({
...validatePrimeNumber(value as number),
value: value as number,
});
};
return (
);
};
export default App;
```
### 自定义校验
我们提供了 `validateStatus` `help` `hasFeedback` 等属性,你可以不通过 Form 自己定义校验的时机和内容。
1. `validateStatus`: 校验状态,可选 'success', 'warning', 'error', 'validating'。
2. `hasFeedback`:用于给输入框添加反馈图标。
3. `help`:设置校验文案。
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import {
Cascader,
DatePicker,
Form,
Input,
InputNumber,
Mentions,
Select,
TimePicker,
TreeSelect,
} from 'antd';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 },
},
};
const App: React.FC = () => (
} />
-
);
export default App;
```
### 动态校验规则
根据不同情况执行不同的校验规则。
```tsx
import React, { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Input } from 'antd';
const formItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8 },
};
const formTailLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8, offset: 4 },
};
const App: React.FC = () => {
const [form] = Form.useForm();
const [checkNick, setCheckNick] = useState(false);
useEffect(() => {
form.validateFields(['nickname']);
}, [checkNick, form]);
const onCheckboxChange = (e: { target: { checked: boolean } }) => {
setCheckNick(e.target.checked);
};
const onCheck = async () => {
try {
const values = await form.validateFields();
console.log('Success:', values);
} catch (errorInfo) {
console.log('Failed:', errorInfo);
}
};
return (
Nickname is required
Check
);
};
export default App;
```
### 校验与更新依赖
Form.Item 可以通过 `dependencies` 属性,设置关联字段。当关联字段的值发生变化时,会触发校验与更新。
```tsx
import React from 'react';
import { Alert, Form, Input, Typography } from 'antd';
const App: React.FC = () => {
const [form] = Form.useForm();
return (
{/* Field */}
({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('The new password that you entered do not match!'));
},
}),
]}
>
{/* Render Props */}
{() => (
Only Update when password2 updated:
{JSON.stringify(form.getFieldsValue(), null, 2)}
)}
);
};
export default App;
```
### 滑动到错误字段
校验失败时/手动滚动到错误字段。
```tsx
import React from 'react';
import { Button, Flex, Form, Input, Select } from 'antd';
const App = () => {
const [form] = Form.useForm();
return (
form.scrollToField('bio')}>Scroll to Bio
Submit
form.resetFields()}>
Reset
);
};
export default App;
```
### 校验其他组件
以上演示没有出现的表单控件对应的校验演示。
```tsx
import React from 'react';
import { InboxOutlined, UploadOutlined } from '@ant-design/icons';
import {
Button,
Checkbox,
Col,
ColorPicker,
Form,
InputNumber,
Radio,
Rate,
Row,
Select,
Slider,
Space,
Switch,
Upload,
} from 'antd';
const formItemLayout = {
labelCol: { span: 6 },
wrapperCol: { span: 14 },
};
const normFile = (e: any) => {
console.log('Upload event:', e);
if (Array.isArray(e)) {
return e;
}
return e?.fileList;
};
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const App: React.FC = () => (
China
machines
item 1
item 2
item 3
item 1
item 2
item 3
A
B
C
D
E
F
}>Click to upload
Click or drag file to this area to upload
Support for a single or bulk upload.
Submit
reset
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Form 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Button, Form, Input, Space } from 'antd';
import type { FormProps, GetProp } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
padding: token.padding,
maxWidth: 800,
marginTop: 32,
backgroundColor: token.colorBgContainer,
borderRadius: token.borderRadius,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
},
}));
const stylesObject: FormProps['styles'] = {
label: {
textAlign: 'end',
color: '#333',
fontWeight: 500,
},
content: {
paddingInlineStart: 12,
},
};
const stylesFunction: FormProps['styles'] = (info): GetProp => {
if (info.props.variant === 'filled') {
return {
root: {
border: '1px solid #1677FF',
},
label: {
textAlign: 'end',
color: '#1677FF',
},
content: {
paddingInlineStart: 12,
},
};
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
const sharedProps: FormProps = {
labelCol: { span: 4 },
wrapperCol: { span: 20 },
autoComplete: 'off',
classNames,
};
const sharedFormContent = (
<>
Submit
reset
>
);
return (
<>
>
);
};
export default App;
```
### getValueProps + normalize
配合 `getValueProps` 和 `normalize`,可以转换 `value` 的格式,如将时间戳转成 `dayjs` 对象再传给 `DatePicker`。
```tsx
import React from 'react';
import type { FormProps } from 'antd';
import { Button, DatePicker, Form } from 'antd';
import dayjs from 'dayjs';
const dateTimestamp = dayjs('2024-01-01').valueOf();
type FieldType = {
date?: string;
};
const onFinish: FormProps['onFinish'] = (values) => {
console.log('Success:', values);
};
const App: React.FC = () => (
label="Date"
name="date"
rules={[{ required: true }]}
getValueProps={(value) => ({ value: value && dayjs(Number(value)) })}
normalize={(value) => value && `${dayjs(value).valueOf()}`}
>
Submit
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Form
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| colon | 配置 Form.Item 的 `colon` 的默认值。表示是否显示 label 后面的冒号 (只有在属性 layout 为 horizontal 时有效) | boolean | true | | 4.18.0 |
| disabled | 设置表单组件禁用,仅对 antd 组件有效 | boolean | false | 4.21.0 | × |
| component | 设置 Form 渲染元素,为 `false` 则不创建 DOM 节点 | ComponentType \| false | form | | × |
| fields | 通过状态管理(如 redux)控制表单字段,如非强需求不推荐使用。查看[示例](#form-demo-global-state) | [FieldData](#fielddata)\[] | - | | × |
| form | 经 `Form.useForm()` 创建的 form 控制实例,不提供时会自动创建 | [FormInstance](#forminstance) | - | | × |
| feedbackIcons | 当 `Form.Item` 有 `hasFeedback` 属性时可以自定义图标 | [FeedbackIcons](#feedbackicons) | - | 5.9.0 | × |
| initialValues | 表单默认值,只有初始化以及重置时生效 | object | - | | × |
| labelAlign | label 标签的文本对齐方式 | `left` \| `right` | `right` | | 6.4.0 |
| labelWrap | label 标签的文本换行方式 | boolean | false | 4.18.0 | × |
| labelCol | label 标签布局,同 ` ` 组件,设置 `span` `offset` 值,如 `{span: 3, offset: 12}` 或 `sm: {span: 3, offset: 12}` | [object](/components/grid-cn#col) | - | | × |
| layout | 表单布局 | `horizontal` \| `vertical` \| `inline` | `horizontal` | | × |
| name | 表单名称,会作为表单字段 `id` 前缀使用 | string | - | | × |
| preserve | 当字段被删除时保留字段值。你可以通过 `getFieldsValue(true)` 来获取保留字段值 | boolean | true | 4.4.0 | × |
| requiredMark | 必选样式,可以切换为必选或者可选展示样式。此为 Form 配置,Form.Item 无法单独配置 | boolean \| `optional` \| ((label: ReactNode, info: { required: boolean }) => ReactNode) | true | `renderProps`: 5.9.0 | 4.8.0 |
| scrollToFirstError | 提交失败自动滚动到第一个错误字段 | boolean \| [Options](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options) \| { focus: boolean } | false | focus: 5.24.0 | 5.2.0 |
| size | 设置字段组件的尺寸(仅限 antd 组件) | `small` \| `medium` \| `large` | - | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| tooltip | 配置提示属性 | [TooltipProps](/components/tooltip-cn#api) & { icon?: ReactNode } | - | 6.3.0 | 6.3.0 |
| validateMessages | 验证提示模板,说明[见下](#validatemessages) | [ValidateMessages](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134) | - | | 4.0.0 |
| validateTrigger | 统一设置字段触发验证的时机 | string \| string\[] | `onChange` | 4.3.0 | × |
| variant | 表单内控件变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 | 5.19.0 |
| wrapperCol | 需要为输入控件设置布局样式时,使用该属性,用法同 labelCol | [object](/components/grid-cn#col) | - | | × |
| onFieldsChange | 字段更新时触发回调事件 | function(changedFields, allFields) | - | | × |
| onFinish | 提交表单且数据验证成功后回调事件 | function(values) | - | | × |
| onFinishFailed | 提交表单且数据验证失败后回调事件 | function({ values, errorFields, outOfDate }) | - | | × |
| onValuesChange | 字段值更新时触发回调事件 | function(changedValues, allValues) | - | | × |
| clearOnDestroy | 当表单被卸载时清空表单值 | boolean | false | 5.18.0 | × |
> 支持原生 form 除 `onSubmit` 外的所有属性。
### validateMessages
Form 为验证提供了[默认的错误提示信息](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134),你可以通过配置 `validateMessages` 属性,修改对应的提示模板。一种常见的使用方式,是配置国际化提示信息:
```jsx
const validateMessages = {
required: "'${name}' 是必选字段",
// ...
};
;
```
此外,[ConfigProvider](/components/config-provider-cn) 也提供了全局化配置方案,允许统一配置错误提示模板:
```jsx
const validateMessages = {
required: "'${name}' 是必选字段",
// ...
};
;
```
## Form.Item
表单字段组件,用于数据双向绑定、校验、布局等。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| colon | 配合 `label` 属性使用,表示是否显示 `label` 后面的冒号 | boolean | true | |
| dependencies | 设置依赖字段,说明[见下](#dependencies) | [NamePath](#namepath)\[] | - | |
| extra | 额外的提示信息,和 `help` 类似,当需要错误信息和提示文案同时出现时,可以使用这个。 | ReactNode | - | |
| getValueFromEvent | 设置如何将 event 的值转换成字段值 | (..args: any\[]) => any | - | |
| getValueProps | 为子元素添加额外的属性 (不建议通过 `getValueProps` 生成动态函数 prop,请直接将其传递给子组件) | (value: any) => Record | - | 4.2.0 |
| hasFeedback | 配合 `validateStatus` 属性使用,展示校验状态图标,建议只配合 Input 组件使用 此外,它还可以通过 Icons 属性获取反馈图标。 | boolean \| { icons: [FeedbackIcons](#feedbackicons) } | false | icons: 5.9.0 |
| help | 提示信息,如不设置,则会根据校验规则自动生成 | ReactNode | - | |
| hidden | 是否隐藏字段(依然会收集和校验字段) | boolean | false | 4.4.0 |
| htmlFor | 设置子元素 label `htmlFor` 属性 | string | - | |
| initialValue | 设置子元素默认值,如果与 Form 的 `initialValues` 冲突则以 Form 为准 | string | - | 4.2.0 |
| label | `label` 标签的文本,当不需要 label 又需要与冒号对齐,可以设为 null | ReactNode | - | null: 5.22.0 |
| labelAlign | 标签文本对齐方式 | `left` \| `right` | `right` | |
| labelCol | `label` 标签布局,同 ` ` 组件,设置 `span` `offset` 值,如 `{span: 3, offset: 12}` 或 `sm: {span: 3, offset: 12}`。你可以通过 Form 的 `labelCol` 进行统一设置,不会作用于嵌套 Item。当和 Form 同时设置时,以 Item 为准 | [object](/components/grid-cn#col) | - | |
| messageVariables | 默认验证字段的信息,查看[详情](#messagevariables) | Record<string, string> | - | 4.7.0 |
| name | 字段名,支持数组 | [NamePath](#namepath) | - | |
| normalize | 组件获取值后进行转换,再放入 Form 中。不支持异步 | (value, prevValue, prevValues) => any | - | |
| noStyle | 为 `true` 时不带样式,作为纯字段控件使用。当自身没有 `validateStatus` 而父元素存在有 `validateStatus` 的 Form.Item 会继承父元素的 `validateStatus` | boolean | false | |
| preserve | 当字段被删除时保留字段值 | boolean | true | 4.4.0 |
| required | 必填样式设置。如不设置,则会根据校验规则自动生成 | boolean | false | |
| rules | 校验规则,设置字段的校验逻辑。点击[此处](#form-demo-basic)查看示例 | [Rule](#rule)\[] | - | |
| shouldUpdate | 自定义字段更新逻辑,说明[见下](#shouldupdate) | boolean \| (prevValue, curValue) => boolean | false | |
| tooltip | 配置提示信息 | ReactNode \| ([TooltipProps](/components/tooltip-cn#api) & { icon?: ReactNode }) | - | 4.7.0 |
| trigger | 设置收集字段值变更的时机。点击[此处](#form-demo-customized-form-controls)查看示例 | string | `onChange` | |
| validateFirst | 当某一规则校验不通过时,是否停止剩下的规则的校验。设置 `parallel` 时会并行校验 | boolean \| `parallel` | false | `parallel`: 4.5.0 |
| validateDebounce | 设置防抖,延迟毫秒数后进行校验 | number | - | 5.9.0 |
| validateStatus | 校验状态,如不设置,则会根据校验规则自动生成,可选:'success' 'warning' 'error' 'validating' | string | - | |
| validateTrigger | 设置字段校验的时机 | string \| string\[] | `onChange` | |
| valuePropName | 子节点的值的属性。注意:Switch、Checkbox 的 valuePropName 应该是 `checked`,否则无法获取这个两个组件的值。该属性为 `getValueProps` 的封装,自定义 `getValueProps` 后会失效 | string | `value` | |
| wrapperCol | 需要为输入控件设置布局样式时,使用该属性,用法同 `labelCol`。你可以通过 Form 的 `wrapperCol` 进行统一设置,不会作用于嵌套 Item。当和 Form 同时设置时,以 Item 为准 | [object](/components/grid-cn#col) | - | |
| layout | 表单项布局 | `horizontal` \| `vertical` | - | 5.18.0 |
被设置了 `name` 属性的 `Form.Item` 包装的控件,表单控件会自动添加 `value`(或 `valuePropName` 指定的其他属性) `onChange`(或 `trigger` 指定的其他属性),数据同步将被 Form 接管,这会导致以下结果:
1. 你**不再需要也不应该**用 `onChange` 来做数据收集同步(你可以使用 Form 的 `onValuesChange`),但还是可以继续监听 `onChange` 事件。
2. 你不能用控件的 `value` 或 `defaultValue` 等属性来设置表单域的值,默认值可以用 Form 里的 `initialValues` 来设置。注意 `initialValues` 不能被 `setState` 动态更新,你需要用 `setFieldsValue` 来更新。
3. 你不应该用 `setState`,可以使用 `form.setFieldsValue` 来动态改变表单值。
### dependencies
当字段间存在依赖关系时使用。如果一个字段设置了 `dependencies` 属性。那么它所依赖的字段更新时,该字段将自动触发更新与校验。一种常见的场景,就是注册用户表单的“密码”与“确认密码”字段。“确认密码”校验依赖于“密码”字段,设置 `dependencies` 后,“密码”字段更新会重新触发“校验密码”的校验逻辑。你可以参考[具体例子](#form-demo-dependencies)。
`dependencies` 不应和 `shouldUpdate` 一起使用,因为这可能带来更新逻辑的混乱。
### FeedbackIcons
`({ status: ValidateStatus, errors: ReactNode, warnings: ReactNode }) => Record`
### shouldUpdate
Form 通过增量更新方式,只更新被修改的字段相关组件以达到性能优化目的。大部分场景下,你只需要编写代码或者与 [`dependencies`](#dependencies) 属性配合校验即可。而在某些特定场景,例如修改某个字段值后出现新的字段选项、或者纯粹希望表单任意变化都对某一个区域进行渲染。你可以通过 `shouldUpdate` 修改 Form.Item 的更新逻辑。
当 `shouldUpdate` 为 `true` 时,Form 的任意变化都会使该 Form.Item 重新渲染。这对于自定义渲染一些区域十分有帮助,要注意 Form.Item 里包裹的子组件必须由函数返回,否则 `shouldUpdate` 不会起作用:
相关issue:[#34500](https://github.com/ant-design/ant-design/issues/34500)
```jsx
{() => {
return {JSON.stringify(form.getFieldsValue(), null, 2)} ;
}}
```
你可以参考[示例](#form-demo-inline-login)查看具体使用场景。
当 `shouldUpdate` 为方法时,表单的每次数值更新都会调用该方法,提供原先的值与当前的值以供你比较是否需要更新。这对于是否根据值来渲染额外字段十分有帮助:
```jsx
prevValues.additional !== curValues.additional}>
{() => {
return (
);
}}
```
你可以参考[示例](#form-demo-control-hooks)查看具体使用场景。
### messageVariables
你可以通过 `messageVariables` 修改 Form.Item 的默认验证信息。
```jsx
user}
rules={[{ required: true, message: '${label} is required' }]}
>
```
自 `5.20.2` 起,当你希望不要转译 `${}` 时,你可以通过 `\\${}` 来跳过:
```jsx
{ required: true, message: '${label} is convert, \\${label} is not convert' }
// good is convert, ${label} is not convert
```
## Form.List
为字段提供数组化管理。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| children | 渲染函数 | (fields: Field\[], operation: { add, remove, move }, meta: { errors }) => React.ReactNode | - | |
| initialValue | 设置子元素默认值,如果与 Form 的 `initialValues` 冲突则以 Form 为准 | any\[] | - | 4.9.0 |
| name | 字段名,支持数组。List 本身也是字段,因而 `getFieldsValue()` 默认会返回 List 下所有值,你可以通过[参数](#getfieldsvalue)改变这一行为 | [NamePath](#namepath) | - | |
| rules | 校验规则,仅支持自定义规则。需要配合 [ErrorList](#formerrorlist) 一同使用。 | { validator, message }\[] | - | 4.7.0 |
```tsx
{(fields) =>
fields.map((field) => (
))
}
```
注意:Form.List 下的字段不应该配置 `initialValue`,你始终应该通过 Form.List 的 `initialValue` 或者 Form 的 `initialValues` 来配置。
## operation
Form.List 渲染表单相关操作函数。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ------ | ---------- | -------------------------------------------------- | ----------- | ----- |
| add | 新增表单项 | (defaultValue?: any, insertIndex?: number) => void | insertIndex | 4.6.0 |
| move | 移动表单项 | (from: number, to: number) => void | - | |
| remove | 删除表单项 | (index: number \| number\[]) => void | number\[] | 4.5.0 |
## Form.ErrorList
4.7.0 新增。错误展示组件,仅限配合 Form.List 的 rules 一同使用。参考[示例](#form-demo-dynamic-form-item)。
| 参数 | 说明 | 类型 | 默认值 |
| ------ | -------- | ------------ | ------ |
| errors | 错误列表 | ReactNode\[] | - |
## Form.Provider
提供表单间联动功能,其下设置 `name` 的 Form 更新时,会自动触发对应事件。查看[示例](#form-demo-form-context)。
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| onFormChange | 子表单字段更新时触发 | function(formName: string, info: { changedFields, forms }) | - |
| onFormFinish | 子表单提交时触发 | function(formName: string, info: { values, forms }) | - |
```jsx
{
if (name === 'form1') {
// Do something...
}
}}
>
```
### FormInstance
| 名称 | 说明 | 类型 | 版本 |
| --- | --- | --- | --- |
| getFieldError | 获取对应字段名的错误信息 | (name: [NamePath](#namepath)) => string\[] | |
| getFieldInstance | 获取对应字段实例 | (name: [NamePath](#namepath)) => any | 4.4.0 |
| getFieldsError | 获取一组字段名对应的错误信息,返回为数组形式 | (nameList?: [NamePath](#namepath)\[]) => FieldError\[] | |
| getFieldsValue | 获取一组字段名对应的值,会按照对应结构返回。默认返回现存字段值,当调用 `getFieldsValue(true)` 时返回所有值 | [GetFieldsValue](#getfieldsvalue) | |
| getFieldValue | 获取对应字段名的值 | (name: [NamePath](#namepath)) => any | |
| isFieldsTouched | 检查一组字段是否被用户操作过,`allTouched` 为 `true` 时检查是否所有字段都被操作过 | (nameList?: [NamePath](#namepath)\[], allTouched?: boolean) => boolean | |
| isFieldTouched | 检查对应字段是否被用户操作过 | (name: [NamePath](#namepath)) => boolean | |
| isFieldValidating | 检查对应字段是否正在校验 | (name: [NamePath](#namepath)) => boolean | |
| resetFields | 重置一组字段到 `initialValues` | (fields?: [NamePath](#namepath)\[]) => void | |
| scrollToField | 滚动到对应字段位置 | (name: [NamePath](#namepath), options: [ScrollOptions](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options) \| { focus: boolean }) => void | focus: 5.24.0 |
| setFields | 设置一组字段状态 | (fields: [FieldData](#fielddata)\[]) => void | |
| setFieldValue | 设置表单的值(该值将直接传入 form store 中并且**重置错误信息**。如果你不希望传入对象被修改,请克隆后传入) | (name: [NamePath](#namepath), value: any) => void | 4.22.0 |
| setFieldsValue | 设置表单的值(该值将直接传入 form store 中并且**重置错误信息**。如果你不希望传入对象被修改,请克隆后传入)。如果你只想修改 Form.List 中单项值,请通过 `setFieldValue` 进行指定 | (values) => void | |
| submit | 提交表单,与点击 `submit` 按钮效果相同 | () => void | |
| validateFields | 触发表单验证,设置 `recursive` 时会递归校验所有包含的路径 | (nameList?: [NamePath](#namepath)\[], config?: [ValidateConfig](#validatefields)) => Promise | |
#### validateFields
```tsx
export interface ValidateConfig {
// 5.5.0 新增。仅校验内容而不会将错误信息展示到 UI 上。
validateOnly?: boolean;
// 5.9.0 新增。对提供的 `nameList` 与其子路径进行递归校验。
recursive?: boolean;
// 5.11.0 新增。校验 dirty 的字段(touched + validated)。
// 使用 `dirty` 可以很方便的仅校验用户操作过和被校验过的字段。
dirty?: boolean;
}
```
返回示例:
```jsx
validateFields()
.then((values) => {
/*
values:
{
username: 'username',
password: 'password',
}
*/
})
.catch((errorInfo) => {
/*
errorInfo:
{
values: {
username: 'username',
password: 'password',
},
errorFields: [
{ name: ['password'], errors: ['Please input your Password!'] },
],
outOfDate: false,
}
*/
});
```
## Hooks
### Form.useForm
`type Form.useForm = (): [FormInstance]`
创建 Form 实例,用于管理所有数据状态。
### Form.useFormInstance
`type Form.useFormInstance = (): FormInstance`
`4.20.0` 新增,获取当前上下文正在使用的 Form 实例,常见于封装子组件消费无需透传 Form 实例:
```tsx
const Sub = () => {
const form = Form.useFormInstance();
return form.setFieldsValue({})} />;
};
export default () => {
const [form] = Form.useForm();
return (
);
};
```
### Form.useWatch
`type Form.useWatch = (namePath: NamePath | (selector: (values: Store) => any), formInstance?: FormInstance | WatchOptions): Value`
`5.12.0` 新增 `selector`
用于直接获取 form 中字段对应的值。通过该 Hooks 可以与诸如 `useSWR` 进行联动从而降低维护成本:
```tsx
const Demo = () => {
const [form] = Form.useForm();
const userName = Form.useWatch('username', form);
const { data: options } = useSWR(`/api/user/${userName}`, fetcher);
return (
);
};
```
如果你的组件被包裹在 `Form.Item` 内部,你可以省略第二个参数,`Form.useWatch` 会自动找到上层最近的 `FormInstance`。
`useWatch` 默认只监听在 Form 中注册的字段,如果需要监听非注册字段,可以通过配置 `preserve` 进行监听:
```tsx
const Demo = () => {
const [form] = Form.useForm();
const age = Form.useWatch('age', { form, preserve: true });
console.log(age);
return (
form.setFieldValue('age', 2)}>Update
);
};
```
### Form.Item.useStatus
`type Form.Item.useStatus = (): { status: ValidateStatus | undefined, errors: ReactNode[], warnings: ReactNode[] }`
`4.22.0` 新增,可用于获取当前 Form.Item 的校验状态,如果上层没有 Form.Item,`status` 将会返回 `undefined`。`5.4.0` 新增 `errors` 和 `warnings`,可用于获取当前 Form.Item 的错误信息和警告信息:
```tsx
const CustomInput = ({ value, onChange }) => {
const { status, errors } = Form.Item.useStatus();
return (
);
};
export default () => (
);
```
#### 与其他获取数据的方式的区别
Form 仅会对变更的 Field 进行刷新,从而避免完整的组件刷新可能引发的性能问题。因而你无法在 render 阶段通过 `form.getFieldsValue` 来实时获取字段值,而 `useWatch` 提供了一种特定字段访问的方式,从而使得在当前组件中可以直接消费字段的值。同时,如果为了更好的渲染性能,你可以通过 Field 的 renderProps 仅更新需要更新的部分。而当当前组件更新或者 effect 都不需要消费字段值时,则可以通过 `onValuesChange` 将数据抛出,从而避免组件更新。
## Interface
### NamePath
`string | number | (string | number)[]`
### GetFieldsValue
`getFieldsValue` 提供了多种重载方法:
#### getFieldsValue(nameList?: true | [NamePath](#namepath)\[], filterFunc?: FilterFunc)
当不提供 `nameList` 时,返回所有注册字段,这也包含 List 下所有的值(即便 List 下没有绑定 Item)。
当 `nameList` 为 `true` 时,返回 store 中所有的值,包含未注册字段。例如通过 `setFieldsValue` 设置了不存在的 Item 的值,也可以通过 `true` 全部获取。
当 `nameList` 为数组时,返回规定路径的值。需要注意的是,`nameList` 为嵌套数组。例如你需要某路径值应该如下:
```tsx
// 单个路径
form.getFieldsValue([['user', 'age']]);
// 多个路径
form.getFieldsValue([
['user', 'age'],
['preset', 'account'],
]);
```
#### getFieldsValue({ filter?: FilterFunc })
### FilterFunc
用于过滤一些字段值,`meta` 会返回字段相关信息。例如可以用来获取仅被用户修改过的值等等。
```tsx
type FilterFunc = (meta: { touched: boolean; validating: boolean }) => boolean;
```
### FieldData
| 名称 | 说明 | 类型 |
| ---------- | ---------------- | ------------------------ |
| errors | 错误信息 | string\[] |
| warnings | 警告信息 | string\[] |
| name | 字段名称 | [NamePath](#namepath)\[] |
| touched | 是否被用户操作过 | boolean |
| validating | 是否正在校验 | boolean |
| value | 字段对应值 | any |
### Rule
Rule 支持接收 object 进行配置,也支持 function 来动态获取 form 的数据:
```tsx
type Rule = RuleConfig | ((form: FormInstance) => RuleConfig);
```
| 名称 | 说明 | 类型 | 版本 |
| --- | --- | --- | --- |
| defaultField | 仅在 `type` 为 `array` 类型时有效,用于指定数组元素的校验规则 | [rule](#rule) | |
| enum | 是否匹配枚举中的值(需要将 `type` 设置为 `enum`) | any\[] | |
| fields | 仅在 `type` 为 `array` 或 `object` 类型时有效,用于指定子元素的校验规则 | Record<string, [rule](#rule)> | |
| len | string 类型时为字符串长度;number 类型时为确定数字; array 类型时为数组长度 | number | |
| max | 必须设置 `type`:string 类型为字符串最大长度;number 类型时为最大值;array 类型时为数组最大长度 | number | |
| message | 错误信息,不设置时会通过[模板](#validatemessages)自动生成 | string \| ReactElement | |
| min | 必须设置 `type`:string 类型为字符串最小长度;number 类型时为最小值;array 类型时为数组最小长度 | number | |
| pattern | 正则表达式匹配 | RegExp | |
| required | 是否为必选字段 | boolean | |
| transform | 将字段值转换成目标值后进行校验 | (value) => any | |
| type | 类型,常见有 `string` \| `number` \| `boolean` \| `url` \| `email` \| `tel`。更多请参考[此处](https://github.com/react-component/async-validator#type) | string | |
| validateTrigger | 设置触发验证时机,必须是 Form.Item 的 `validateTrigger` 的子集 | string \| string\[] | |
| validator | 自定义校验,接收 Promise 作为返回值。[示例](#form-demo-register)参考 | ([rule](#rule), value) => Promise | |
| warningOnly | 仅警告,不阻塞表单提交 | boolean | 4.17.0 |
| whitespace | 如果字段仅包含空格则校验不通过,只在 `type: 'string'` 时生效 | boolean | |
### WatchOptions
| 名称 | 说明 | 类型 | 默认值 | 版本 |
| -------- | ------------------------------------- | ------------ | ---------------------- | ----- |
| form | 指定 Form 实例 | FormInstance | 当前 context 中的 Form | 5.4.0 |
| preserve | 是否监视没有对应的 `Form.Item` 的字段 | boolean | false | 5.4.0 |
## Semantic DOM
https://ant.design/components/form-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Form)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| inlineItemMarginBottom | 行内布局表单项间距 | number | 0 |
| itemMarginBottom | 表单项间距 | number | 24 |
| labelColonMarginInlineEnd | 标签冒号后间距 | number | 8 |
| labelColonMarginInlineStart | 标签冒号前间距 | number | 2 |
| labelColor | 标签颜色 | string | rgba(0,0,0,0.88) |
| labelFontSize | 标签字体大小 | number | 14 |
| labelHeight | 标签高度 | string \| number | 32 |
| labelRequiredMarkColor | 必填项标记颜色 | string | #ff4d4f |
| verticalLabelMargin | 垂直布局标签外边距 | Margin \| undefined | 0 |
| verticalLabelPadding | 垂直布局标签内边距 | Padding \| undefined | 0 0 8px |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorSuccess | 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| controlOutline | 控制输入组件的外轮廓线颜色。 | string | |
| controlOutlineWidth | 控制输入组件的外轮廓线宽度。 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginLG | 控制元素外边距,大尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationFast | 动效播放速度,快速。用于小型元素动画交互 | string | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| motionEaseOut | 预设动效曲率 | string | |
| motionEaseOutBack | 预设动效曲率 | string | |
| paddingSM | 控制元素的小内间距。 | number | |
| screenLGMax | 控制大屏幕的最大宽度。 | number | |
| screenMDMax | 控制中等屏幕的最大宽度。 | number | |
| screenSMMax | 控制小屏幕的最大宽度。 | number | |
| screenXSMax | 控制超小屏幕的最大宽度。 | number | |
## FAQ
### Segmented 为什么不能被 Form `disabled` 禁用? {#faq-segmented-cannot-disabled}
Segmented 设计上为数据展示类组件,而非表单控件组件。虽然它可以作为类似 Radio 的表单控件使用,但并非为此设计。因而行为上更类似于 Tabs 组件,不会被 Form 的 `disabled` 所禁用。相关讨论参考 [#54749](https://github.com/ant-design/ant-design/pull/54749#issuecomment-3797737096)。
### Switch、Checkbox 为什么不能绑定数据? {#faq-switch-checkbox-binding}
Form.Item 默认绑定值属性到 `value` 上,而 Switch、Checkbox 等组件的值属性为 `checked`。你可以通过 `valuePropName` 来修改绑定的值属性。
```tsx | pure
```
### name 为数组时的转换规则? {#faq-name-array-rule}
当 `name` 为数组时,会按照顺序填充路径。当存在数字且 form store 中没有该字段时会自动转变成数组。因而如果需要数组为 key 时请使用 string 如:`['1', 'name']`。
### 为何在 Modal 中调用 form 控制台会报错? {#faq-form-modal-error}
> Warning: Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?
这是因为你在调用 form 方法时,Modal 还未初始化导致 form 没有关联任何 Form 组件。你可以通过给 Modal 设置 `forceRender` 将其预渲染。示例点击[此处](https://codesandbox.io/s/antd-reproduction-template-ibu5c)。
### 为什么 Form.Item 下的子组件 `defaultValue` 不生效? {#faq-item-default-value}
当你为 Form.Item 设置 `name` 属性后,子组件会转为受控模式。因而 `defaultValue` 不会生效。你需要在 Form 上通过 `initialValues` 设置默认值。
### 为什么第一次调用 `ref` 的 Form 为空? {#faq-ref-first-call}
`ref` 仅在节点被加载时才会被赋值,请参考 React 官方文档:
### 为什么 `resetFields` 会重新 mount 组件? {#faq-reset-fields-mount}
`resetFields` 会重置整个 Field,因而其子组件也会重新 mount 从而消除自定义组件可能存在的副作用(例如异步数据、状态等等)。
### Form 的 initialValues 与 Item 的 initialValue 区别? {#faq-initial-values-diff}
在大部分场景下,我们总是推荐优先使用 Form 的 `initialValues`。只有存在动态字段时你才应该使用 Item 的 `initialValue`。默认值遵循以下规则:
1. Form 的 `initialValues` 拥有最高优先级
2. Field 的 `initialValue` 次之 \*. 多个同 `name` Item 都设置 `initialValue` 时,则 Item 的 `initialValue` 不生效
### 为什么 `getFieldsValue` 在初次渲染的时候拿不到值? {#faq-get-fields-value}
`getFieldsValue` 默认返回收集的字段数据,而在初次渲染时 Form.Item 节点尚未渲染,因而无法收集到数据。你可以通过 `getFieldsValue(true)` 来获取所有字段数据。
### 为什么 `setFieldsValue` 设置字段为 `undefined` 时,有的组件不会重置为空? {#faq-set-fields-undefined}
在 React 中,`value` 从确定值改为 `undefined` 表示从受控变为非受控,因而不会重置展示值(但是 Form 中的值确实已经改变)。你可以通过 HOC 改变这一逻辑:
```jsx
const MyInput = ({
// 强制保持受控逻辑
value = '',
...rest
}) => ;
;
```
### 为什么字段设置 `rules` 后更改值 `onFieldsChange` 会触发三次? {#faq-rules-trigger-three-times}
字段除了本身的值变化外,校验也是其状态之一。因而在触发字段变化会经历以下几个阶段:
1. Trigger value change
2. Rule validating
3. Rule validated
在触发过程中,调用 `isFieldValidating` 会经历 `false` > `true` > `false` 的变化过程。
### 为什么 Form.List 不支持 `label` 还需要使用 ErrorList 展示错误? {#faq-form-list-no-label}
Form.List 本身是 renderProps,内部样式非常自由。因而默认配置 `label` 和 `error` 节点很难与之配合。如果你需要 antd 样式的 `label`,可以通过外部包裹 Form.Item 来实现。
### 为什么 Form.Item 的 `dependencies` 对 Form.List 下的字段没有效果? {#faq-dependencies-form-list}
Form.List 下的字段需要包裹 Form.List 本身的 `name`,比如:
```tsx
{(fields) =>
fields.map((field) => (
))
}
```
依赖则是:`['users', 0, 'name']`
### 为什么 `normalize` 不能是异步方法? {#faq-normalize-async}
React 中异步更新会导致受控组件交互行为异常。当用户交互触发 `onChange` 后,通过异步改变值会导致组件 `value` 不会立刻更新,使得组件呈现假死状态。如果你需要异步触发变更,请通过自定义组件实现内部异步状态。
### `scrollToFirstError` 和 `scrollToField` 失效? {#faq-scroll-not-working}
1. 使用了自定义表单控件
类似问题:[#28370](https://github.com/ant-design/ant-design/issues/28370) [#27994](https://github.com/ant-design/ant-design/issues/27994)
从 `5.17.0` 版本开始,滑动操作将优先使用表单控件元素所转发的 ref 元素。因此,在考虑自定义组件支持校验滚动时,请优先考虑将其转发给表单控件元素。
滚动依赖于表单控件元素上绑定的 `id` 字段,如果自定义控件没有将 `id` 赋到正确的元素上,这个功能将失效。你可以参考这个 [codesandbox](https://codesandbox.io/s/antd-reproduction-template-forked-25nul?file=/index.js)。
2. 页面内有多个表单
页面内如果有多个表单,且存在表单项 `name` 重复,表单滚动定位可能会查找到另一个表单的同名表单项上。需要给表单 `Form` 组件设置不同的 `name` 以区分。
### 继上,为何不通过 `ref` 绑定元素? {#faq-ref-binding}
当自定义组件不支持 `ref` 时,Form 无法获取子元素真实 DOM 节点,而通过包裹 Class Component 调用 `findDOMNode` 会在 React Strict Mode 下触发警告。因而我们使用 id 来进行元素定位。
### `setFieldsValue` 不会触发 `onFieldsChange` 和 `onValuesChange`? {#faq-set-fields-no-trigger}
是的,change 事件仅当用户交互才会触发。该设计是为了防止在 change 事件中调用 `setFieldsValue` 导致的循环问题。如果仅仅需要组件内消费,可以通过 `useWatch` 或者 `Field.renderProps` 来实现。
### 为什么 `dependencies` 不能响应 `setFieldsValue` 触发的更新? {#faq-dependencies-set-fields}
`dependencies` 主要用于字段间的校验联动,依赖字段由用户交互触发更新时,会重新触发当前字段的更新与校验。如果需要根据 `setFieldsValue` 后的值变化来渲染额外内容或切换字段选项,请使用 `shouldUpdate` 或 `useWatch`。
### 为什么 Form.Item 嵌套子组件后,不更新表单值? {#faq-item-nested-update}
Form.Item 在渲染时会注入 `value` 与 `onChange` 事件给子元素,当你的字段组件被包裹时属性将无法传递。所以以下代码是不会生效的:
```jsx
I am a wrapped Input
```
你可以通过 HOC 自定义组件形式来解决这个问题:
```jsx
const MyInput = (props) => (
I am a wrapped Input
);
;
```
### 为什么表单点击 label 会更改组件状态? {#faq-label-click-change}
> 相关 issue:[#47031](https://github.com/ant-design/ant-design/issues/47031),[#43175](https://github.com/ant-design/ant-design/issues/43175), [#52152](https://github.com/ant-design/ant-design/issues/52152)
表单 label 使用 [HTML label](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/label) 元素来包裹表单控件,从而实现点击 label 时聚焦到对应控件。这是 label 元素的原生行为,用于提升可访问性和用户体验,这种标准交互模式能让用户更容易操作表单控件。如果你不希望这种行为,可通过 `htmlFor={null}` 属性解除关联,通常不建议这样做。
```diff
-
+
```
### 有更多参考文档吗? {#faq-more-docs}
- 你可以阅读[《antd v4 Form 使用心得》](https://zhuanlan.zhihu.com/p/375753910)获得一些使用帮助以及建议。
- 想在 DatePicker、Switch 也使用 before、after?可以参考[《如何优雅的对 Form.Item 的 children 增加 before、after》](https://zhuanlan.zhihu.com/p/422752055)。
- 优雅的 Form + Modal 结合使用方案[《如何优雅的使用 Form + Modal》](https://zhuanlan.zhihu.com/p/388222294)。
---
## grid-cn
Source: https://ant.design/components/grid-cn.md
---
category: Components
group: 布局
title: Grid
subtitle: 栅格
description: 24 栅格系统。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*mfJeS6cqZrEAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*DLUwQ4B2_zQAAAAAAAAAAAAADrJ8AQ/original
---
## 设计理念 {#design-concept}
在多数业务情况下,Ant Design 需要在设计区域内解决大量信息收纳的问题,因此在 12 栅格系统的基础上,我们将整个设计建议区域按照 24 等分的原则进行划分。
划分之后的信息区块我们称之为『盒子』。建议横向排列的盒子数量最多四个,最少一个。『盒子』在整个屏幕上占比见上图。设计部分基于盒子的单位定制盒子内部的排版规则,以保证视觉层面的舒适感。
## 概述 {#overview}
布局的栅格化系统,我们是基于行(row)和列(col)来定义信息区块的外部框架,以保证页面的每个区域能够稳健地排布起来。下面简单介绍一下它的工作原理:
- 通过 `row` 在水平方向建立一组 `column`(简写 col)。
- 你的内容应当放置于 `col` 内,并且,只有 `col` 可以作为 `row` 的直接元素。
- 栅格系统中的列是指 1 到 24 的值来表示其跨越的范围。例如,三个等宽的列可以使用 ` ` 来创建。
- 如果一个 `row` 中的 `col` 总和超过 24,那么多余的 `col` 会作为一个整体另起一行排列。
我们的栅格化系统基于 Flex 布局,允许子元素在父节点内的水平对齐方式 - 居左、居中、居右、等宽排列、分散排列。子元素与子元素之间,支持顶部对齐、垂直居中对齐、底部对齐的方式。同时,支持使用 order 来定义元素的排列顺序。
布局是基于 24 栅格来定义每一个『盒子』的宽度,但不拘泥于栅格。
## 代码演示 {#examples}
### 基础栅格
从堆叠到水平排列。
使用单一的一组 `Row` 和 `Col` 栅格组件,就可以创建一个基本的栅格系统,所有列(Col)必须放在 `Row` 内。
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
<>
col
col-12
col-12
col-8
col-8
col-8
col-6
col-6
col-6
col-6
>
);
export default App;
```
### 区块间隔
栅格常常需要和间隔进行配合,你可以使用 `Row` 的 `gutter` 属性,我们推荐使用 `(16+8n)px` 作为栅格间隔(n 是自然数)。
如果要支持响应式,可以写成 `{ xs: 8, sm: 16, md: 24, lg: 32 }`。
如果需要垂直间距,可以写成数组形式 `[水平间距, 垂直间距]` `[16, { xs: 8, sm: 16, md: 24, lg: 32 }]`。
`Row` 的 `gutter` 属性可以设置为[字符串CSS单位](https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Values_and_Units),例如:`px`、`rem`、`vw`、`vh` 等。
> 数组形式垂直间距在 `3.24.0` 之后支持。string 类型在 `5.28.0` 之后支持。
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const style: React.CSSProperties = {
padding: '8px 0',
backgroundColor: '#0092ff',
};
const App: React.FC = () => (
<>
Horizontal
col-6
col-6
col-6
col-6
Responsive
col-6
col-6
col-6
col-6
Vertical
col-6
col-6
col-6
col-6
col-6
col-6
col-6
col-6
Gutter(string)
col-6
col-6
col-6
col-6
>
);
export default App;
```
### 左右偏移
列偏移。
使用 `offset` 可以将列向右侧偏。例如,`offset={4}` 将元素向右侧偏移了 4 个列(column)的宽度。
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
<>
col-8
col-8
col-6 col-offset-6
col-6 col-offset-6
col-12 col-offset-6
>
);
export default App;
```
### 栅格排序
列排序。
通过使用 `push` 和 `pull` 类就可以很容易的改变列(column)的顺序。
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
col-18 col-push-6
col-6 col-pull-18
);
export default App;
```
### 排版
布局基础。
子元素根据不同的值 `start`、`center`、`end`、`space-between`、`space-around` 和 `space-evenly`,分别定义其在父节点里面的排版方式。
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css } = props;
return {
rowContainer: css`
background-color: rgba(128, 128, 128, 0.08);
`,
};
});
const App: React.FC = () => {
const { styles } = useStyles();
return (
<>
sub-element align left
col-4
col-4
col-4
col-4
sub-element align center
col-4
col-4
col-4
col-4
sub-element align right
col-4
col-4
col-4
col-4
sub-element monospaced arrangement
col-4
col-4
col-4
col-4
sub-element align full
col-4
col-4
col-4
col-4
sub-element align evenly
col-4
col-4
col-4
col-4
>
);
};
export default App;
```
### 对齐
子元素垂直对齐。
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css } = props;
return {
rowContainer: css`
background-color: rgba(128, 128, 128, 0.08);
`,
};
});
const DemoBox: React.FC> = (props) => {
const { value, children } = props;
return {children}
;
};
const App: React.FC = () => {
const { styles } = useStyles();
return (
<>
Align Top
col-4
col-4
col-4
col-4
Align Middle
col-4
col-4
col-4
col-4
Align Bottom
col-4
col-4
col-4
col-4
>
);
};
export default App;
```
### 排序
通过 `order` 来改变元素的排序。
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css } = props;
return {
rowContainer: css`
background-color: rgba(128, 128, 128, 0.08);
`,
};
});
const App: React.FC = () => {
const { styles } = useStyles();
return (
<>
Normal
1 col-order-4
2 col-order-3
3 col-order-2
4 col-order-1
Responsive
1 col-order-responsive
2 col-order-responsive
3 col-order-responsive
4 col-order-responsive
>
);
};
export default App;
```
### Flex 填充
Col 提供 `flex` 属性以支持填充。
```tsx
import React from 'react';
import { Col, Divider, Row } from 'antd';
const App: React.FC = () => (
<>
Percentage columns
2 / 5
3 / 5
Fill rest
100px
Fill Rest
Raw flex style
1 1 200px
0 1 300px
none
auto with no-wrap
>
);
export default App;
```
### 响应式布局
参照 Bootstrap 的 [响应式设计](http://getbootstrap.com/css/#grid-media-queries),预设七个响应尺寸:`xs` `sm` `md` `lg` `xl` `xxl` `xxxl`。
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
Col
Col
Col
);
export default App;
```
### Flex 响应式布局
支持更灵活的响应式下的任意 flex 比例,该功能需要浏览器支持 CSS Variables。
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
{Array.from({ length: 10 }).map((_, index) => {
const key = `col-${index}`;
return (
Col
);
})}
);
export default App;
```
### 其他属性的响应式
`span` `pull` `push` `offset` `order` 属性可以通过内嵌到 `xs` `sm` `md` `lg` `xl` `xxl` 属性中来使用。
其中 `xs={6}` 相当于 `xs={{ span: 6 }}`。
```tsx
import React from 'react';
import { Col, Row } from 'antd';
const App: React.FC = () => (
Col
Col
Col
);
export default App;
```
### 栅格配置器
可以简单配置几种等分栅格和间距。
```tsx
import React, { useState } from 'react';
import { Col, Row, Slider } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css, cssVar } = props;
return {
colContainer: css`
border: 0;
padding-block: 0 !important;
background-color: transparent !important;
`,
box: css`
height: 120px;
font-size: ${cssVar.fontSize};
line-height: 120px;
background-color: #0092ff;
border-radius: ${cssVar.borderRadiusSM};
`,
code: css`
direction: ltr;
padding: ${cssVar.paddingXS} ${cssVar.padding};
font-size: ${cssVar.fontSize};
background-color: #f9f9f9;
border-radius: ${cssVar.borderRadius};
`,
};
});
const gutters: Record = {};
const vgutters: Record = {};
const colCounts: Record = {};
[8, 16, 24, 32, 40, 48].forEach((value, i) => {
gutters[i] = value;
});
[8, 16, 24, 32, 40, 48].forEach((value, i) => {
vgutters[i] = value;
});
[2, 3, 4, 6, 8, 12].forEach((value, i) => {
colCounts[i] = value;
});
const App: React.FC = () => {
const { styles } = useStyles();
const [gutterKey, setGutterKey] = useState(1);
const [vgutterKey, setVgutterKey] = useState(1);
const [colCountKey, setColCountKey] = useState(2);
const cols: React.ReactNode[] = [];
const colCount = colCounts[colCountKey];
let colCode = '';
for (let i = 0; i < colCount; i++) {
cols.push(
Column
,
);
colCode += ` \n`;
}
return (
<>
Horizontal Gutter (px):
gutters[value as number] }}
/>
Vertical Gutter (px):
vgutters[value as number] }}
/>
Column Count:
colCounts[value as number] }}
/>
{cols}
{cols}
Another Row:
{cols}
{`\n${colCode}\n${colCode}
`}
{`\n${colCode}
`}
>
);
};
export default App;
```
### useBreakpoint Hook
使用 `useBreakpoint` Hook 个性化布局,其中 `xs` 仅当满足最小宽度时生效。
```tsx
import React from 'react';
import { Grid, Tag } from 'antd';
const { useBreakpoint } = Grid;
const App: React.FC = () => {
const screens = useBreakpoint();
return (
<>
Current break point:{' '}
{Object.entries(screens)
.filter((screen) => !!screen[1])
.map((screen) => (
{screen[0]}
))}
>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
Ant Design 的布局组件若不能满足你的需求,你也可以直接使用社区的优秀布局组件:
- [react-flexbox-grid](https://roylee0704.github.io/react-flexbox-grid/)
- [react-blocks](https://github.com/whoisandy/react-blocks/)
### Row
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| align | 垂直对齐方式 | `top` \| `middle` \| `bottom` \| `stretch` \| `{[key in 'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'xxl' \| 'xxxl']: 'top' \| 'middle' \| 'bottom' \| 'stretch'}` | `top` | object: 4.24.0 | × |
| gutter | 栅格间隔,可以写成[字符串CSS单位](https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Values_and_Units)或支持响应式的对象写法来设置水平间隔 { xs: 8, sm: 16, md: 24}。或者使用数组形式同时设置 `[水平间距, 垂直间距]` | number \| string \| object \| array | 0 | string: 5.28.0 | × |
| justify | 水平排列方式 | `start` \| `end` \| `center` \| `space-around` \| `space-between` \| `space-evenly` \| `{[key in 'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl' \| 'xxl' \| 'xxxl']: 'start' \| 'end' \| 'center' \| 'space-around' \| 'space-between' \| 'space-evenly'}` | `start` | object: 4.24.0 | × |
| wrap | 是否自动换行 | boolean | true | 4.8.0 | × |
### Col
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| flex | flex 布局属性。数字类型对应 'flex: n n auto';字符串类型直接透传(例如纯数字字符串 'n' 对应 'flex: n 1 0') | string \| number | - | | × |
| offset | 栅格左侧的间隔格数,间隔内不可以有栅格 | number | 0 | | × |
| order | 栅格顺序 | number | 0 | | × |
| pull | 栅格向左移动格数 | number | 0 | | × |
| push | 栅格向右移动格数 | number | 0 | | × |
| span | 栅格占位格数,为 0 时相当于 `display: none` | number | - | | × |
| xs | `窗口宽度 < 576px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | | × |
| sm | `窗口宽度 ≥ 576px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | | × |
| md | `窗口宽度 ≥ 768px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | | × |
| lg | `窗口宽度 ≥ 992px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | | × |
| xl | `窗口宽度 ≥ 1200px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | | × |
| xxl | `窗口宽度 ≥ 1600px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | | × |
| xxxl | `窗口宽度 ≥ 1920px` 响应式栅格,可为栅格数或一个包含其他属性的对象 | number \| object | - | 6.3.0 | × |
您可以使用 [主题定制](/docs/react/customize-theme-cn) 修改 `screen[XS|SM|MD|LG|XL|XXL|XXXL]` 来修改断点值(自 5.1.0 起,[codesandbox demo](https://codesandbox.io/s/antd-reproduction-template-forked-dlq3r9?file=/index.js))。
响应式栅格的断点扩展自 [BootStrap 4 的规则](https://getbootstrap.com/docs/4.0/layout/overview/#responsive-breakpoints)(不包含链接里 `occasionally` 的部分)。
## 主题变量(Design Token){#design-token}
---
## icon-cn
Source: https://ant.design/components/icon-cn.md
---
category: Components
subtitle: 图标
description: 语义化的矢量图形。
group: 通用
title: Icon
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*PdAYS7anRpoAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*xEDOTJx2DEkAAAAAAAAAAAAADrJ8AQ/original
---
## 使用方法 {#how-to-use}
使用图标组件,你需要安装 [@ant-design/icons](https://github.com/ant-design/ant-design-icons) 图标组件包:
:::info{title=温馨提示}
使用 antd@6.x 版本时, 请确保安装配套的 `@ant-design/icons@6.x` 版本,避免版本不匹配带来的 Context 问题。详见 [#53275](https://github.com/ant-design/ant-design/issues/53275#issuecomment-2747448317)
:::
## 设计师专属 {#designers-exclusive}
安装 [Kitchen Sketch 插件 💎](https://kitchen.alipay.com),就可以一键拖拽使用 Ant Design 和 Iconfont 的海量图标,还可以关联自有项目。
## 图标列表 {#list-of-icons}
## 代码演示 {#examples}
### 基本用法
通过 `@ant-design/icons` 引用 Icon 组件,不同主题的 Icon 组件名为图标名加主题做为后缀,也可以通过设置 `spin` 属性来实现动画旋转效果。
```tsx
import React from 'react';
import {
HomeOutlined,
LoadingOutlined,
SettingFilled,
SmileOutlined,
SyncOutlined,
} from '@ant-design/icons';
import { Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 多色图标
双色图标可以通过 `twoToneColor` 属性设置主题色。
```tsx
import React from 'react';
import { CheckCircleTwoTone, HeartTwoTone, SmileTwoTone } from '@ant-design/icons';
import { Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义图标
利用 `Icon` 组件封装一个可复用的自定义图标。可以通过 `component` 属性传入一个组件来渲染最终的图标,以满足特定的需求。
```tsx
import React from 'react';
import Icon, { HomeOutlined } from '@ant-design/icons';
import { Space } from 'antd';
import type { GetProps } from 'antd';
type CustomIconComponentProps = GetProps;
const HeartSvg: React.FC = () => (
heart icon
);
const PandaSvg: React.FC = () => (
Panda icon
);
const HeartIcon: React.FC> = (props) => (
);
const PandaIcon: React.FC> = (props) => (
);
const App: React.FC = () => (
);
export default App;
```
### 使用 iconfont.cn
对于使用 [iconfont.cn](https://iconfont.cn/) 的用户,通过设置 `createFromIconfontCN` 方法参数对象中的 `scriptUrl` 字段, 即可轻松地使用已有项目中的图标。
```tsx
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
import { Space } from 'antd';
const IconFont = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js',
});
const App: React.FC = () => (
);
export default App;
```
### 使用 iconfont.cn 的多个资源
`@ant-design/icons@4.1.0` 以后,`scriptUrl` 可引用多个资源,用户可灵活的管理 [iconfont.cn](https://iconfont.cn/) 图标。如果资源的图标出现重名,会按照数组顺序进行覆盖。
```tsx
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
import { Space } from 'antd';
const IconFont = createFromIconfontCN({
scriptUrl: [
'//at.alicdn.com/t/font_1788044_0dwu4guekcwr.js', // icon-javascript, icon-java, icon-shoppingcart (overridden)
'//at.alicdn.com/t/font_1788592_a5xf2bdic3u.js', // icon-shoppingcart, icon-python
],
});
const App: React.FC = () => (
);
export default App;
```
## API
从 4.0 开始,antd 不再内置 Icon 组件,请使用独立的包 `@ant-design/icons`。
### 通用图标 {#common-icon}
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| className | 设置图标的样式名 | string | - | | × |
| rotate | 图标旋转角度(IE9 无效) | number | - | | × |
| spin | 是否有旋转动画 | boolean | false | | × |
| style | 设置图标的样式,例如 `fontSize` 和 `color` | CSSProperties | - | | × |
| twoToneColor | 仅适用双色图标。设置双色图标的主要颜色,或主要颜色和次要颜色 | string \| \[string, string] | - | | × |
其中我们提供了三种主题的图标,不同主题的 Icon 组件名为图标名加主题做为后缀。
```jsx
import { StarOutlined, StarFilled, StarTwoTone } from '@ant-design/icons';
```
### 自定义 Icon {#custom-icon}
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| component | 控制如何渲染图标,通常是一个渲染根标签为 `` 的 React 组件 | ComponentType<CustomIconComponentProps> | - | | × |
| rotate | 图标旋转角度(IE9 无效) | number | - | | × |
| spin | 是否有旋转动画 | boolean | false | | × |
| style | 设置图标的样式,例如 `fontSize` 和 `color` | CSSProperties | - | | × |
### 关于 SVG 图标 {#about-svg-icons}
在 `3.9.0` 之后,我们使用了 SVG 图标替换了原先的 font 图标,从而带来了以下优势:
- 完全离线化使用,不需要从 CDN 下载字体文件,图标不会因为网络问题呈现方块,也无需字体文件本地部署。
- 在低端设备上 SVG 有更好的清晰度。
- 支持多色图标。
- 对于内建图标的更换可以提供更多 API,而不需要进行样式覆盖。
更多讨论可参考:[#10353](https://github.com/ant-design/ant-design/issues/10353)。
所有的图标都会以 `` 标签渲染,可以使用 `style` 和 `className` 设置图标的大小和单色图标的颜色。例如:
```jsx
import { MessageOutlined } from '@ant-design/icons';
;
```
### 双色图标主色 {#set-two-tone-color}
对于双色图标,可以通过使用 `getTwoToneColor()` 和 `setTwoToneColor(colorString)` 来全局设置图标主色。
```jsx
import { getTwoToneColor, setTwoToneColor } from '@ant-design/icons';
setTwoToneColor('#eb2f96');
getTwoToneColor(); // #eb2f96
```
### 自定义 font 图标 {#custom-font-icon}
在 `3.9.0` 之后,我们提供了一个 `createFromIconfontCN` 方法,方便开发者调用在 [iconfont.cn](https://iconfont.cn/) 上自行管理的图标。
```jsx
import React from 'react';
import { createFromIconfontCN } from '@ant-design/icons';
import ReactDOM from 'react-dom/client';
const MyIcon = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js', // 在 iconfont.cn 上生成
});
ReactDOM.createRoot(mountNode).render( );
```
其本质上是创建了一个使用 `` 标签来渲染图标的组件。
options 的配置项如下:
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| extraCommonProps | 给所有的 `svg` 图标 ` ` 组件设置额外的属性 | { \[key: string]: any } | {} | | × |
| scriptUrl | [iconfont.cn](https://iconfont.cn/) 项目在线生成的 js 地址,`@ant-design/icons@4.1.0` 之后支持 `string[]` 类型 | string \| string\[] | - | | × |
在 `scriptUrl` 都设置有效的情况下,组件在渲染前会自动引入 [iconfont.cn](https://iconfont.cn/) 项目中的图标符号集,无需手动引入。
见 [iconfont.cn 使用帮助](https://iconfont.cn/help/detail?spm=a313x.7781069.1998910419.15&helptype=code) 查看如何生成 js 地址。
### 自定义 SVG 图标 {#custom-svg-icon}
如果使用 `webpack`,可以通过配置 [@svgr/webpack](https://www.npmjs.com/package/@svgr/webpack) 来将 `svg` 图标作为 `React` 组件导入。`@svgr/webpack` 的 `options` 选项请参阅 [svgr 文档](https://github.com/smooth-code/svgr#options)。
```js
// webpack.config.js
module.exports = {
// ... other config
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'babel-loader',
},
{
loader: '@svgr/webpack',
options: {
babel: false,
icon: true,
},
},
],
};
```
如果使用 `vite`,可以通过配置 [vite-plugin-svgr](https://www.npmjs.com/package/vite-plugin-svgr) 来将 `svg` 图标作为 `React` 组件导入。`vite-plugin-svgr` 的 `options` 选项请参阅 [svgr 文档](https://github.com/smooth-code/svgr#options)。
```js
// vite.config.js
export default defineConfig(() => ({
// ... other config
plugins: [svgr({ svgrOptions: { icon: true } })],
}));
```
```jsx
import React from 'react';
import Icon from '@ant-design/icons';
import MessageSvg from 'path/to/message.svg'; // 你的 '*.svg' 文件路径
// import MessageSvg from 'path/to/message.svg?react'; // 使用vite 你的 '*.svg?react' 文件路径.
import ReactDOM from 'react-dom/client';
// in create-react-app:
// import { ReactComponent as MessageSvg } from 'path/to/message.svg';
ReactDOM.createRoot(mountNode).render( );
```
`Icon` 中的 `component` 组件的接受的属性如下:
| 字段 | 说明 | 类型 | 只读值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| className | 计算后的 `svg` 类名 | string | - | | × |
| fill | `svg` 元素填充的颜色 | string | `currentColor` | | × |
| height | `svg` 元素高度 | string \| number | `1em` | | × |
| style | 计算后的 `svg` 元素样式 | CSSProperties | - | | × |
| width | `svg` 元素宽度 | string \| number | `1em` | | × |
## 主题变量(Design Token){#design-token}
## FAQ
### 为什么有时 icon 注入的样式会引起全局样式异常?{#faq-icon-bad-style}
相关 issue:[#54391](https://github.com/ant-design/ant-design/issues/54391)
启用 `layer` 时,icon 的样式可能会使 `@layer antd` 优先级降低,并导致所有组件样式异常。
这个问题可以通过以下两步解决:
1. 使用 `@ant-design/icons@6.x` 配合 `antd@6.x`。
2. 停止使用 `message`, `Modal` 和 `notification` 的静态方法,改为使用 hooks 版本或 App 提供的实例。
如果无法避免使用静态方法,可以在 App 组件下立刻使用任一一个 icon 组件,以规避静态方法对样式的影响。
```diff
+ {/* any icon */}
+
{/* your pages */}
```
---
## image-cn
Source: https://ant.design/components/image-cn.md
---
category: Components
group: 数据展示
title: Image
subtitle: 图片
description: 可预览的图片。
cols: 2
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*FbOCS6aFMeUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*LVQ3R5JjjJEAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 需要展示图片时使用。
- 加载显示大图或加载失败时容错处理。
## 代码演示 {#examples}
### 基本用法
单击图像可以放大显示。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 渐进加载
通过 `placeholder` 属性设置占位符。当 `placeholder` 为 `{ progress: true }` 时显示水彩墨水加载动画;设置为 `{ progress: { percent: number } }` 时显示进度条;也可以传入自定义 React 节点作为占位符。
```tsx
import React, { useEffect, useState } from 'react';
import { Button, Flex, Image, theme } from 'antd';
const GeneratingProgress: React.FC = () => {
const { token } = theme.useToken();
const [percent, setPercent] = useState(0);
const [status, setStatus] = useState<'idle' | 'generating' | 'complete'>('idle');
const imageStyles = {
root: { borderRadius: token.borderRadiusLG },
image: { borderRadius: token.borderRadiusLG },
cover: { borderRadius: token.borderRadiusLG },
};
useEffect(() => {
if (status === 'generating' && percent < 100) {
const timer = setTimeout(() => {
setPercent((prev) => Math.min(prev + Math.random() * 8 + 2, 100));
}, 200);
return () => clearTimeout(timer);
} else if (status === 'generating' && percent >= 100) {
const timer = setTimeout(() => {
setStatus('complete');
}, 200);
return () => clearTimeout(timer);
}
}, [status, percent]);
const handleStart = () => {
setPercent(0);
setStatus('generating');
};
const imageNode =
status === 'complete' ? (
) : (
(
<>
{progress}
Generating {p}%
>
),
},
}}
/>
);
return (
Generate
{imageNode}
);
};
const App: React.FC = () => {
const { token } = theme.useToken();
const [random, setRandom] = useState(() => Date.now());
const imageStyles = {
root: { borderRadius: token.borderRadiusLG },
image: { borderRadius: token.borderRadiusLG },
cover: { borderRadius: token.borderRadiusLG },
};
return (
<>
'loading...' } }}
/>
(
<>
{progress}
Generating {p}%
>
),
},
}}
/>
{
setRandom(Date.now());
}}
>
Reload Image
}
/>
>
);
};
export default App;
```
### 容错处理
加载失败显示图像占位符。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 多张图片预览
点击左右切换按钮可以预览多张图片。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
console.log(`current index: ${current}, prev index: ${prev}`),
}}
>
);
export default App;
```
### 相册模式
从一张图片点开相册。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义预览图片
可以设置不同的预览图片。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 受控的预览
可以使预览受控。
```tsx
import React, { useState } from 'react';
import { Button, Image, InputNumber } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [scaleStep, setScaleStep] = useState(0.5);
return (
<>
scaleStep:{' '}
setScaleStep(val!)}
/>
setOpen(true)}>
show image preview
{
setOpen(value);
},
}}
/>
>
);
};
export default App;
```
### 自定义工具栏
可以自定义工具栏并添加下载原图或翻转旋转后图片的按钮。
```tsx
import React from 'react';
import {
DownloadOutlined,
LeftOutlined,
RightOutlined,
RotateLeftOutlined,
RotateRightOutlined,
SwapOutlined,
UndoOutlined,
ZoomInOutlined,
ZoomOutOutlined,
} from '@ant-design/icons';
import { Image, Space } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles((props) => {
const { css, iconPrefixCls, cssVar } = props;
return {
wrapper: css`
padding: 0 ${cssVar.paddingLG};
color: ${cssVar.colorWhite};
font-size: ${cssVar.fontSizeXL};
background-color: rgba(0, 0, 0, 0.1);
border-radius: 100px;
.${iconPrefixCls} {
padding: ${cssVar.paddingSM};
cursor: pointer;
&:hover {
opacity: 0.3;
}
&[disabled] {
opacity: 0.3;
cursor: not-allowed;
}
}
`,
};
});
const imageList = [
'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
'https://gw.alipayobjects.com/zos/antfincdn/aPkFc8Sj7n/method-draw-image.svg',
];
// you can download flipped and rotated image
// https://codesandbox.io/s/zi-ding-yi-gong-ju-lan-antd-5-7-0-forked-c9jvmp
const App: React.FC = () => {
const { styles } = useStyles();
const [current, setCurrent] = React.useState(0);
// or you can download flipped and rotated image
// https://codesandbox.io/s/zi-ding-yi-gong-ju-lan-antd-5-7-0-forked-c9jvmp
const onDownload = () => {
const url = imageList[current];
const suffix = url.slice(url.lastIndexOf('.'));
const filename = Date.now() + suffix;
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const blobUrl = URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = blobUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(blobUrl);
link.remove();
});
};
return (
(
onActive?.(-1)} />
onActive?.(1)}
/>
),
onChange: (index) => {
setCurrent(index);
},
}}
>
{imageList.map((item, index) => (
))}
);
};
export default App;
```
### 自定义预览内容
可以自定义预览内容。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
(
),
actionsRender: () => null,
}}
src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
/>
);
export default App;
```
### 预览遮罩
遮罩效果。
```tsx
import React from 'react';
import { Image, Space } from 'antd';
const App: React.FC = () => {
return (
blur
),
}}
/>
Dimmed mask
),
}}
/>
No mask
),
}}
/>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Image 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Image } from 'antd';
import type { GetProp, ImageProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 4px;
border-radius: 8px;
overflow: hidden;
`,
}));
const styles: ImageProps['styles'] = {
image: {
borderRadius: '4px',
},
};
const stylesFn: ImageProps['styles'] = (info): GetProp => {
if (info.props.preview) {
return {
root: {
border: '2px solid #A594F9',
borderRadius: 8,
padding: 4,
transition: 'all 0.3s ease',
},
image: {
borderRadius: 4,
filter: 'grayscale(50%)',
},
};
}
return {};
};
const App: React.FC = () => {
const sharedProps: ImageProps = {
src: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
width: 160,
alt: 'Example image',
classNames,
};
return (
);
};
export default App;
```
### 嵌套
嵌套在弹框当中使用
```tsx
import React, { useState } from 'react';
import { Button, Divider, Image, Modal } from 'antd';
const App: React.FC = () => {
const [show1, setShow1] = useState(false);
const [show2, setShow2] = useState(false);
const [show3, setShow3] = useState(false);
return (
<>
{
setShow1(true);
}}
>
showModal
{
setShow1(open);
}}
onCancel={() => {
setShow1(false);
}}
onOk={() => setShow1(false)}
>
{
setShow2(true);
}}
>
test2
{
setShow2(open);
}}
onCancel={() => {
setShow2(false);
}}
onOk={() => setShow2(false)}
>
{
setShow3(true);
}}
>
test3
{
setShow3(open);
}}
onCancel={() => {
setShow3(false);
}}
onOk={() => setShow3(false)}
>
console.log(`current index: ${current}, prev index: ${prev}`),
}}
>
>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Image
| 参数 | 说明 | 类型 | 默认值 | 版本 | [全局配置](/components/config-provider-cn#component-config) |
| --- | --- | --- | --- | --- | --- |
| alt | 图像描述 | string | - | | × |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | | 6.0.0 |
| fallback | 加载失败容错地址 | string | - | | 5.28.0 |
| height | 图像高度 | string \| number | - | | × |
| placeholder | 加载占位,支持 ReactNode 或配置对象 | [PlaceholderType](#placeholdertype) | - | | × |
| preview | 预览参数,为 `false` 时禁用 | boolean \| [PreviewType](#previewtype) | true | | `preview.closeIcon`: 5.14.0,`preview.mask`: 6.0.0,`preview.mask.closable`: 6.4.0 |
| src | 图片地址 | string | - | | × |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | | 6.0.0 |
| width | 图像宽度 | string \| number | - | | × |
| onError | 加载错误回调 | (event: Event) => void | - | | × |
其他属性见 [<img>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes)
### PlaceholderType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| progress | 进度配置,设置为 `true` 显示渐变动画,设置 `{ percent: number }` 显示进度,`render` 自定义渲染 | boolean \| [ImageProgressConfig](#imageprogressconfig) | - | |
### ImageProgressConfig
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| percent | 进度值 | number | - | |
| render | 自定义渲染,接收默认的进度 UI 和百分比 | (progress: React.ReactNode, percent: number) => React.ReactNode | - | |
### PreviewType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| actionsRender | 自定义工具栏渲染 | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| closeIcon | 自定义关闭 Icon | React.ReactNode | - | |
| cover | 自定义预览遮罩 | React.ReactNode \| [CoverConfig](#coverconfig) | - | CoverConfig v6.0 开始支持 |
| focusTrap | 预览打开时是否在预览内捕获焦点 | boolean | true | 6.4.0 |
| ~~destroyOnClose~~ | 关闭预览时销毁子元素,已移除,不再支持 | boolean | false | |
| ~~forceRender~~ | 强制渲染预览图,已移除,不再支持 | boolean | - | |
| getContainer | 指定预览挂载的节点,但依旧为全屏展示,false 为挂载在当前位置 | string \| HTMLElement \| (() => HTMLElement) \| false | - | |
| imageRender | 自定义预览内容 | (originalNode: React.ReactElement, info: { transform: [TransformType](#transformtype), image: [ImgInfo](#imginfo) }) => React.ReactNode | - | |
| mask | 预览遮罩效果 | boolean \| { enabled?: boolean, blur?: boolean, closable?: boolean } | true | mask.closable: 6.4.0 |
| ~~maskClassName~~ | 缩略图遮罩类名,请使用 `classNames.cover` 替换 | string | - | |
| maxScale | 最大缩放倍数 | number | 50 | |
| minScale | 最小缩放倍数 | number | 1 | |
| movable | 预览图片大于视口时是否可拖拽移动 | boolean | true | |
| open | 是否显示预览 | boolean | - | |
| rootClassName | 预览图的根 DOM 类名,会同时作用在图片和预览层最外侧 | string | - | |
| scaleStep | `1 + scaleStep` 为缩放放大的每步倍数 | number | 0.5 | |
| src | 自定义预览 src | string | - | |
| styles | 自定义语义化结构样式 | Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| wheel | 是否启用鼠标滚轮缩放 | boolean | true | 6.6.0 |
| ~~toolbarRender~~ | 自定义工具栏,请使用 `actionsRender` 替换 | (originalNode: React.ReactElement, info: Omit) => React.ReactNode | - | |
| ~~visible~~ | 是否显示,请使用 `open` 替换 | boolean | - | |
| onOpenChange | 预览打开状态变化的回调 | (visible: boolean) => void | - | |
| onTransform | 预览图 transform 变化的回调 | { transform: [TransformType](#transformtype), action: [TransformAction](#transformaction) } | - | |
| ~~onVisibleChange~~ | 当 `visible` 发生改变时的回调,请使用 `onOpenChange` 替换 | (visible: boolean, prevVisible: boolean) => void | - | |
### PreviewGroup
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| fallback | 加载失败容错地址 | string | - | |
| items | 预览数组 | string[] \| { src: string, crossOrigin: string, ... }[] | - | |
| preview | 预览参数,为 `false` 时禁用 | boolean \| [PreviewGroupType](#previewgrouptype) | true | |
### PreviewGroupType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| actionsRender | 自定义工具栏渲染 | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| closeIcon | 自定义关闭 Icon | React.ReactNode | - | |
| countRender | 自定义预览计数内容 | (current: number, total: number) => React.ReactNode | - | |
| focusTrap | 预览打开时是否在预览内捕获焦点 | boolean | true | 6.4.0 |
| current | 当前预览图的 index | number | - | |
| ~~forceRender~~ | 强制渲染预览图,已移除,不再支持 | boolean | - | |
| getContainer | 指定预览挂载的节点,但依旧为全屏展示,false 为挂载在当前位置 | string \| HTMLElement \| (() => HTMLElement) \| false | - | |
| imageRender | 自定义预览内容 | (originalNode: React.ReactElement, info: { transform: [TransformType](#transformtype), image: [ImgInfo](#imginfo), current: number }) => React.ReactNode | - | |
| mask | 预览遮罩效果 | boolean \| { enabled?: boolean, blur?: boolean, closable?: boolean } | true | mask.closable: 6.4.0 |
| ~~maskClassName~~ | 缩略图遮罩类名,请使用 `classNames.cover` 替换 | string | - | |
| minScale | 最小缩放倍数 | number | 1 | |
| maxScale | 最大放大倍数 | number | 50 | |
| movable | 预览图片大于视口时是否可拖拽移动 | boolean | true | |
| open | 是否显示预览 | boolean | - | |
| ~~rootClassName~~ | 预览图的根 DOM 类名,会同时作用在图片和预览层最外侧,请使用 `classNames.root` 替换 | string | - | |
| styles | 自定义语义化结构样式 | Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| wheel | 是否启用鼠标滚轮缩放 | boolean | true | 6.6.0 |
| scaleStep | `1 + scaleStep` 为缩放放大的每步倍数 | number | 0.5 | |
| ~~toolbarRender~~ | 自定义工具栏,请使用 `actionsRender` 替换 | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| ~~visible~~ | 是否显示,请使用 `open` 替换 | boolean | - | |
| onOpenChange | 预览打开状态变化回调,额外携带当前预览图索引 | (visible: boolean, info: { current: number }) => void | - | |
| onChange | 切换预览图的回调 | (current: number, prevCurrent: number) => void | - | |
| onTransform | 预览图 transform 变化的回调 | { transform: [TransformType](#transformtype), action: [TransformAction](#transformaction) } | - | |
| ~~onVisibleChange~~ | 当 `visible` 发生改变时的回调,请使用 `onOpenChange` 替换 | (visible: boolean, prevVisible: boolean, current: number) => void | - | |
## Interface
### TransformType
```typescript
{
x: number;
y: number;
rotate: number;
scale: number;
flipX: boolean;
flipY: boolean;
}
```
### TransformAction
```typescript
type TransformAction =
| 'flipY'
| 'flipX'
| 'rotateLeft'
| 'rotateRight'
| 'zoomIn'
| 'zoomOut'
| 'close'
| 'prev'
| 'next'
| 'wheel'
| 'doubleClick'
| 'move'
| 'dragRebound'
| 'reset';
```
### ToolbarRenderInfoType
```typescript
{
icons: {
flipYIcon: React.ReactNode;
flipXIcon: React.ReactNode;
rotateLeftIcon: React.ReactNode;
rotateRightIcon: React.ReactNode;
zoomOutIcon: React.ReactNode;
zoomInIcon: React.ReactNode;
};
actions: {
onActive?: (index: number) => void; // 5.21.0 之后支持
onFlipY: () => void;
onFlipX: () => void;
onRotateLeft: () => void;
onRotateRight: () => void;
onZoomOut: () => void;
onZoomIn: () => void;
onReset: () => void; // 5.17.3 之后支持
onClose: () => void;
};
transform: TransformType,
current: number;
total: number;
image: ImgInfo
}
```
### ImgInfo
```typescript
{
url: string;
alt: string;
width: string | number;
height: string | number;
}
```
### CoverConfig
```typescript
type CoverConfig = {
coverNode?: React.ReactNode; // 自定义遮罩元素
placement?: 'top' | 'bottom' | 'center'; // 设置预览遮罩显示的位置
};
```
## Semantic DOM
https://ant.design/components/image-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Image)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| previewOperationColor | 预览操作图标颜色 | string | rgba(255,255,255,0.65) |
| previewOperationColorDisabled | 预览操作图标禁用颜色 | string | rgba(255,255,255,0.25) |
| previewOperationHoverColor | 预览操作图标悬浮颜色 | string | rgba(255,255,255,0.85) |
| previewOperationSize | 预览操作图标大小 | number | 18 |
| progressAnimationDuration | 加载动画基础时长 | string | 3s |
| zIndexPopup | 预览浮层 z-index | number | 1080 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| colorBgBase | 用于派生背景色梯度的基础变量,v5 中我们添加了一层背景色的派生算法可以产出梯度明确的背景色的梯度变量。但请不要在代码中直接使用该 Seed Token ! | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgMask | 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer、Image 等组件的蒙层使用的是该 token | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextSecondary | 作为第二梯度的文本色,一般用在不那么需要强化文本颜色的场景,例如 Label 文本、Menu 的文本选中态等场景。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| marginXL | 控制元素外边距,超大尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| motionEaseOut | 预设动效曲率 | string | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingSM | 控制元素的小内间距。 | number | |
---
## input-cn
Source: https://ant.design/components/input-cn.md
---
category: Components
group: 数据录入
title: Input
subtitle: 输入框
description: 通过鼠标或键盘输入内容,是最基础的表单域的包装。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Y3R0RowXHlAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*sBqqTatJ-AkAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 需要用户输入表单域内容时。
- 提供组合型输入框,带搜索的输入框,还可以进行大小选择。
## 代码演示 {#examples}
### 基本使用
基本使用。
```tsx
import React from 'react';
import { Input } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 三种大小
我们为 ` ` 输入框定义了三种尺寸(大、中、小),高度分别为 `40px`、`32px` 和 `24px`。
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Flex, Input } from 'antd';
const App: React.FC = () => (
} />
} />
} />
);
export default App;
```
### 形态变体
Input 形态变体,可选 `outlined` `filled` `borderless` `underlined` 四种形态。
```tsx
import React from 'react';
import { Flex, Input } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 紧凑模式
使用 Space.Compact 创建紧凑模式,更多请查看 [Space.Compact](/components/space-cn#spacecompact) 文档。
```tsx
import React from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Select, Space } from 'antd';
const { Search } = Input;
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
},
{
value: 'jiangsu',
label: 'Jiangsu',
},
];
const App: React.FC = () => (
https://
Submit
);
export default App;
```
### 搜索框
带有搜索按钮的输入框。
```tsx
import React from 'react';
import { AudioOutlined } from '@ant-design/icons';
import { Input, Space } from 'antd';
import type { GetProps } from 'antd';
type SearchProps = GetProps;
const { Search } = Input;
const suffix = ;
const onSearch: SearchProps['onSearch'] = (value, _e, info) => console.log(info?.source, value);
const App: React.FC = () => (
https://
);
export default App;
```
### 搜索框 loading
用于 `onSearch` 的时候展示 `loading`。
```tsx
import React from 'react';
import { Input } from 'antd';
const { Search } = Input;
const App: React.FC = () => (
<>
>
);
export default App;
```
### 文本域
用于多行输入。
```tsx
import React from 'react';
import { Input } from 'antd';
const { TextArea } = Input;
const App: React.FC = () => (
<>
>
);
export default App;
```
### 适应文本高度的文本域
`autoSize` 属性适用于 `textarea` 节点,并且只有高度会自动变化。另外 `autoSize` 可以设定为一个对象,指定最小行数和最大行数。
```tsx
import React, { useState } from 'react';
import { Input } from 'antd';
const { TextArea } = Input;
const App: React.FC = () => {
const [value, setValue] = useState('');
return (
<>