# Ant Design 组件文档
本文件包含所有组件文档的聚合内容。
> 总计 73 个组件
## _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
```
## 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;
```
---
## 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)
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| offsetBottom | 距离窗口底部达到指定偏移量后触发 | number | - |
| offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | 0 |
| target | 设置 `Affix` 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 | () => HTMLElement | () => 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;
```
### 可关闭的警告提示
显示关闭按钮,点击可关闭警告提示。
```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 me to throw a error
);
};
const App: React.FC = () => (
);
export default App;
```
### 操作
可以在右上角自定义操作项。
```tsx
import React from 'react';
import { Alert, Button, Space } from 'antd';
const App: React.FC = () => (
<>
UNDO
}
closable
/>
Detail
}
/>
Done
}
closable
/>
Accept
Decline
}
closable
/>
>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Alert 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Alert, Button, Flex } from 'antd';
import type { AlertProps, AlertSemanticType } 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 } }): AlertSemanticType['styles'] => {
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)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| action | 自定义操作项 | ReactNode | - | 4.9.0 |
| ~~afterClose~~ | 关闭动画结束后触发的回调函数,请使用 `closable.afterClose` 替换 | () => void | - | |
| banner | 是否用作顶部公告 | boolean | false | |
| classNames | 自定义组件内部各语义化结构的类名。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| closable | 可关闭配置,>=5.15.0: 支持 `aria-*` | boolean \| [ClosableType](#closabletype) & React.AriaAttributes | `false` | |
| description | 警告提示的辅助性文字介绍 | ReactNode | - | |
| icon | 自定义图标,`showIcon` 为 true 时有效 | ReactNode | - | |
| ~~message~~ | 警告提示内容,请使用 `title` 替换 | ReactNode | - | |
| title | 警告提示内容 | ReactNode | - | |
| showIcon | 是否显示辅助图标 | boolean | false,`banner` 模式下默认值为 true | |
| styles | 自定义组件内部各语义化结构的内联样式。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| type | 指定警告提示的样式,有四种选择 `success`、`info`、`warning`、`error` | string | `info`,`banner` 模式下默认值为 `warning` | |
| ~~onClose~~ | 关闭时触发的回调函数,请使用 `closable.onClose` 替换 | (e: MouseEvent) => void | - | |
### 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 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| defaultPadding | 默认内间距 | Padding \| undefined | 8px 12px |
| withDescriptionIconSize | 带有描述时的图标尺寸 | number | 24 |
| withDescriptionPadding | 带有描述的内间距 | Padding \| undefined | 20px 24px |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| 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 | |
| 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 | |
| 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 } 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) => {
if (info.props.direction === 'vertical') {
return {
root: {
backgroundColor: 'rgba(255,251,230,0.5)',
height: '100vh',
},
} satisfies AnchorProps['styles'];
}
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| getContainer | 指定滚动的容器 | () => HTMLElement | () => window | |
| getCurrentAnchor | 自定义高亮的锚点 | (activeLink: string) => string | - | |
| offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | | |
| showInkInFixed | `affix={false}` 时是否显示小方块 | boolean | false | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| 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 |
### Link Props
建议使用 items 形式。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ------ | ------------------------------ | --------- | ------ | ---- |
| href | 锚点链接 | string | - | |
| target | 该属性指定在何处显示链接的资源 | string | - | |
| title | 文字内容 | ReactNode | - | |
## 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 MyPage = () => {
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 MyPage = () => {
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 word
;
};
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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}
请确保 App 的 `component` 是一个有效的 html 标签名,以便在启用 CSS 变量时有一个容器来承载 CSS 类名。如果不设置,则默认为 `div` 标签,如果设置为 `false`,则不会创建额外的 DOM 节点,也不会提供默认样式。
---
## 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';
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 = () => (
);
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 } 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 }) => {
if (props.variant === 'filled') {
return {
popup: {
root: { borderWidth: 1, borderColor: '#ccc' },
list: { backgroundColor: 'rgba(240,240,240, 0.85)' },
listItem: { color: '#272727' },
},
} satisfies AutoCompleteProps['styles'];
}
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> | - | |
| defaultActiveFirstOption | 是否默认高亮第一个选项 | boolean | true | |
| defaultOpen | 是否默认展开下拉菜单 | boolean | - | |
| defaultValue | 指定默认选中的条目 | string | - | |
| disabled | 是否禁用 | boolean | false | |
| ~~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` \| `middle` \| `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
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| 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 | |
| colorBgBase | 用于派生背景色梯度的基础变量,v5 中我们添加了一层背景色的派生算法可以产出梯度明确的背景色的梯度变量。但请不要在代码中直接使用该 Seed Token ! | string | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorBorderDisabled | 控制元素在禁用状态下的边框颜色。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBgHover | 错误色的浅色背景色悬浮态 | string | |
| colorErrorHover | 错误色的深色悬浮态 | string | |
| colorErrorOutline | 控制输入组件错误状态下的外轮廓线颜色。 | 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 | |
| colorWarningBg | 警戒色的浅色背景颜色 | string | |
| colorWarningBgHover | 警戒色的浅色背景色悬浮态 | string | |
| colorWarningHover | 警戒色的深色悬浮态 | string | |
| colorWarningOutline | 控制输入组件警告状态下的外轮廓线颜色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| 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;
```
### 响应式尺寸
头像大小可以根据屏幕大小自动调整。
```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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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 | 设置最多显示相关配置,`5.18.0` 前可使用 [参数](https://github.com/ant-design/ant-design/blob/9d134859becbdae5b9ce276f6d9af4264691d81f/components/avatar/group.tsx#L35-L38) | `{ count?: number; style?: CSSProperties; popover?: PopoverProps }` | - | 5.18.0 |
| 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 | 大号头像图标大小 | 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 } 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) => {
if (info.props.size === 'default') {
return {
indicator: {
fontSize: 14,
backgroundColor: '#696FC7',
},
} satisfies BadgeProps['styles'];
}
return {};
};
const ribbonStylesFn: RibbonProps['styles'] = (info) => {
if (info.props.color === '#696FC7') {
return {
content: {
fontWeight: 'bold',
},
indicator: {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
} satisfies RibbonProps['styles'];
}
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| color | 自定义小圆点的颜色 | string | - | |
| count | 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏 | ReactNode | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| dot | 不展示数字,只有一个小红点 | boolean | false | |
| offset | 设置状态点的位置偏移 | \[number, number] | - | |
| overflowCount | 展示封顶的数字值 | number | 99 | |
| showZero | 当数值为 0 时,是否展示 Badge | boolean | false | |
| size | 在设置了 `count` 的前提下有效,设置小圆点的大小 | `default` \| `small` | - | - |
| status | 设置 Badge 为状态点 | `success` \| `processing` \| `default` \| `error` \| `warning` | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| text | 在设置了 `status` 的前提下有效,设置状态点的文本 | ReactNode | - | |
| title | 设置鼠标放在状态点上时显示的文字 | string | - | |
### Badge.Ribbon
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| color | 自定义缎带的颜色 | string | - | |
| placement | 缎带的位置,`start` 和 `end` 随文字方向(RTL 或 LTR)变动 | `start` \| `end` | `end` | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| 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 |
| 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 | |
| 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 | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## 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}
- 当系统拥有超过两级以上的层级结构时;
- 当需要告知用户『你在哪里』时;
- 当需要向上导航的功能时。
```jsx
// >=5.3.0 可用,推荐的写法 ✅
return ;
// <5.3.0 可用,>=5.3.0 时不推荐 🙅🏻♀️
return (
sample
);
// 或
return ;
```
## 代码演示 {#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;
```
### 带有图标的
图标放在文字前面。
```tsx
import React from 'react';
import { HomeOutlined, UserOutlined } from '@ant-design/icons';
import { Breadcrumb } from 'antd';
const App: React.FC = () => (
,
},
{
href: '',
title: (
<>
Application List
>
),
},
{
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 } 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) => {
const items = info.props.items || [];
if (items.length > 2) {
return {
root: { border: '1px solid #F5EFFF', padding: 8, borderRadius: 4 },
item: { color: '#8F87F1' },
} satisfies BreadcrumbProps['styles'];
}
return {};
};
const items = [
{ title: 'Ant Design' },
{ title: Component },
{ title: 'Breadcrumb' },
];
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Breadcrumb
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| dropdownIcon | 自定义下拉图标 | ReactNode | ` ` | 6.2.0 |
| itemRender | 自定义链接函数,和 react-router 配置使用 | (route, params, routes, paths) => ReactNode | - | |
| params | 路由的参数 | object | - | |
| items | 路由栈信息 | [items\[\]](#itemtype) | - | 5.3.0 |
| separator | 分隔符自定义 | ReactNode | `/` | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
### 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`,则尺寸默认为中。
```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 'middle'
return (
<>
setSize(e.target.value)}>
Large
Default
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(({ 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 0.3s;
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.left = `${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 } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `1px solid ${token.colorBorder}`,
borderRadius: token.borderRadius,
padding: `${token.paddingXS}px ${token.padding}px`,
height: 'auto',
},
content: {
color: token.colorText,
},
}));
const stylesObject: ButtonProps['styles'] = {
root: {
boxShadow: '0 1px 2px 0 rgba(0,0,0,0.05)',
},
};
const stylesFn: ButtonProps['styles'] = (info) => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
} satisfies ButtonProps['styles'];
}
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`。
按钮的属性说明如下:
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| autoInsertSpace | 我们默认提供两个汉字之间的空格,可以设置 `autoInsertSpace` 为 `false` 关闭 | boolean | `true` | 5.17.0 |
| block | 将按钮宽度调整为其父宽度的选项 | boolean | false | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| color | 设置按钮的颜色 | `default` \| `primary` \| `danger` \| [PresetColors](#presetcolors) | - | `default`、`primary` 和 `danger`: 5.21.0, `PresetColors`: 5.23.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 | - | |
| ~~iconPosition~~ | 设置按钮图标组件的位置,请使用 `iconPlacement` 替换 | `start` \| `end` | `start` | 5.17.0 |
| iconPlacement | 设置按钮图标组件的位置 | `start` \| `end` | `start` | - |
| loading | 设置按钮载入状态 | boolean \| { delay: number, icon: ReactNode } | false | icon: 5.23.0 |
| shape | 设置按钮形状 | `default` \| `circle` \| `round` | `default` | |
| size | 设置按钮大小 | `large` \| `middle` \| `small` | `middle` | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| target | 相当于 a 链接的 target 属性,href 存在时生效 | string | - | |
| type | 语法糖,设置按钮类型。当设置 `variant` 与 `color` 时以后者为准 | `primary` \| `dashed` \| `link` \| `text` \| `default` | `default` | |
| onClick | 点击按钮时的回调 | (event: React.MouseEvent) => void | - | |
| variant | 设置按钮的变体 | `outlined` \| `dashed` \| `solid` \| `filled` \| `text` \| `link` | - | 5.21.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 | |
| 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 type { Dayjs } from 'dayjs';
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:
}
return listData || [];
};
const getMonthData = (value: Dayjs) => {
if (value.month() === 8) {
return 1394;
}
};
const App: React.FC = () => {
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;
```
### 卡片模式
用于嵌套在空间有限的容器中。
```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: `1px solid ${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 { clsx } from 'clsx';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { HolidayUtil, Lunar } from 'lunar-typescript';
const useStyle = createStyles(({ 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: 1px solid ${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 300ms;
border-radius: ${token.borderRadiusOuter}px;
border: 1px solid transparent;
box-sizing: border-box;
}
&:hover:before {
background: rgba(0, 0, 0, 0.04);
}
`,
today: css`
&:before {
border: 1px solid ${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: rgba(0, 0, 0, 0.04);
}
`,
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, selectInfo) => {
if (selectInfo.source === 'date') {
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 = [];
let current = value.clone();
const localeData = value.localeData();
const months = [];
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 = [];
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: `1px solid ${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 } 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) => {
if (info.props.fullscreen) {
return {
root: {
border: '2px solid #BDE3C3',
borderRadius: 10,
backgroundColor: 'rgba(189,227,195, 0.3)',
},
} satisfies CalendarProps['styles'];
}
};
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');
```
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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> | - | |
| 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: 'middle',
}}
>
{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 } 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: `1px solid ${token.colorBorderSecondary}`,
},
header: {
borderBottom: 'none',
paddingBottom: 8,
},
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) => {
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',
},
} satisfies CardProps['styles'];
}
};
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
卡片内容
```
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| actions | 卡片操作组,位置在卡片底部 | Array<ReactNode> | - | |
| activeTabKey | 当前激活页签的 key | string | - | |
| ~~bordered~~ | 是否有边框, 请使用 `variant` 替换 | boolean | true | |
| variant | 形态变体 | `outlined` \| `borderless` \| | `outlined` | 5.24.0 |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| cover | 卡片封面 | ReactNode | - | |
| defaultActiveTabKey | 初始化选中页签的 key,如果没有设置 activeTabKey | string | `第一个页签的 key` | |
| extra | 卡片右上角的操作区域 | ReactNode | - | |
| hoverable | 鼠标移过时可浮起 | boolean | false | |
| loading | 当卡片内容还在加载中时,可以用 loading 展示一个占位 | boolean | false | |
| size | card 的尺寸 | `default` \| `small` | `default` | |
| 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> | - | |
| onTabChange | 页签切换的回调 | (key) => void | - | |
### Card.Grid
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------- | ---------------------- | ------------- | ------ | ---- |
| className | 网格容器类名 | string | - | |
| hoverable | 鼠标移过时可浮起 | boolean | true | |
| style | 定义网格容器类名的样式 | CSSProperties | - | |
### Card.Meta
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ----------- | ------------------ | ------------- | ------ | ---- |
| avatar | 头像/图标 | ReactNode | - | |
| className | 容器类名 | string | - | |
| description | 描述内容 | ReactNode | - | |
| style | 定义容器类名的样式 | CSSProperties | - | |
| 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)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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 } 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) => {
if (info.props.variant === 'filled') {
return {
prefix: {
color: '#1890ff',
},
suffix: {
color: '#1890ff',
},
popup: {
listItem: {
color: '#1890ff',
},
},
} satisfies CascaderProps['styles'];
}
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
```
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| allowClear | 支持清除 | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: 支持对象形式 |
| ~~autoClearSearchValue~~ | 是否在选中项后清空搜索框,只在 `multiple` 为 `true` 时有效 | boolean | true | 5.9.0 |
| changeOnSelect | 单选时生效(multiple 下始终都可以选择),点选每级菜单选项值都会发生变化。 | boolean | false | |
| className | 自定义类名 | string | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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 |
| ~~dropdownRender~~ | 自定义下拉框内容,请使用 `popupRender` 替换 | (menus: ReactNode) => ReactNode | - | 4.4.0 |
| popupRender | 自定义下拉框内容 | (menus: ReactNode) => ReactNode | - | |
| ~~dropdownStyle~~ | 下拉菜单的 style 属性,使用 `styles.popup.root` 替换 | CSSProperties | - | |
| expandIcon | 自定义次级菜单展开图标 | ReactNode | - | 4.4.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 | - | |
| 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 |
| showSearch | 在选择框中显示搜索框 | boolean \| [Object](#showsearch) | false | |
| size | 输入框大小 | `large` \| `middle` \| `small` | - | |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| suffixIcon | 自定义的选择框后缀图标 | ReactNode | - | |
| value | 指定选中项 | string\[] \| number\[] | - | |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 |
| onChange | 选择完成后的回调 | (value, selectedOptions) => void | - | |
| ~~onDropdownVisibleChange~~ | 显示/隐藏浮层的回调,请使用 `onOpenChange` 替换 | (value) => void | - | 4.17.0 |
| onOpenChange | 显示/隐藏浮层的回调 | (value) => void | - | |
| multiple | 支持多选节点 | boolean | - | 4.17.0 |
| showCheckedStrategy | 定义选中项回填的方式(仅在 `multiple` 为 `true` 时生效)。`Cascader.SHOW_CHILD`: 只显示选中的子节点。`Cascader.SHOW_PARENT`: 只显示父节点(当父节点下所有子节点都选中时)。 | `Cascader.SHOW_PARENT` \| `Cascader.SHOW_CHILD` | `Cascader.SHOW_PARENT` | 4.20.0 |
| removeIcon | 自定义的多选框清除图标 | ReactNode | - | |
| ~searchValue~ | 设置搜索的值,需要与 `showSearch` 配合使用 | string | - | 4.17.0 |
| ~onSearch~ | 监听搜索,返回输入的值 | (search: string) => void | - | 4.17.0 |
| ~~dropdownMenuColumnStyle~~ | 下拉菜单列的样式,请使用 `popupMenuColumnStyle` 替换 | CSSProperties | - | |
| popupMenuColumnStyle | 下拉菜单列的样式 | 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 |
### 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.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 } 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) => {
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| checked | 指定当前是否选中 | boolean | false | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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> | - | |
#### 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 = () => (
<>
Default 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;
```
### 隐藏箭头
你可以通过 `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';
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 = () => (
{text},
},
]}
/>
{text},
},
]}
/>
{text},
},
]}
/>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Collapse 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Collapse, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
import type { CollapseProps } from '..';
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 }) => {
if (props.size === 'large') {
return {
root: {
backgroundColor: '#fff',
border: '1px solid #696FC7',
borderRadius: 8,
},
header: {
backgroundColor: '#F5EFFF',
padding: '12px 16px',
color: '#141414',
},
} satisfies CollapseProps['styles'];
}
};
const App: React.FC = () => {
const sharedProps: CollapseProps = { classNames, items };
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Collapse
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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 | - | |
| expandIconPlacement | 设置图标位置 | `start` \| `end` | `start` | - |
| ~~expandIconPosition~~ | 设置图标位置,请使用 `expandIconPlacement` 替换 | `start` \| `end` | - | 4.21.0 |
| ghost | 使折叠面板透明且无边框 | boolean | false | 4.4.0 |
| size | 设置折叠面板大小 | `large` \| `middle` \| `small` | `middle` | 5.2.0 |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| 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 |
| headerBg | 折叠面板头部背景 | string | rgba(0,0,0,0.02) |
| headerPadding | 折叠面板头部内边距 | Padding \| undefined | 12px 16px |
## 全局 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 } 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) => {
if (info.props.size === 'large') {
return {
popup: {
root: {
border: '1px solid #722ed1',
},
},
} satisfies ColorPickerProps['styles'];
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyles();
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> 自 `antd@5.5.0` 版本开始提供该组件。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| :-- | :-- | :-- | :-- | :-- |
| allowClear | 允许清除选择的颜色 | boolean | false | |
| arrow | 配置弹出的箭头 | `boolean \| { pointAtCenter: boolean }` | true | |
| children | 颜色选择器的触发器 | React.ReactNode | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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` \| `middle` \| `small` | `middle` | 5.7.0 |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| 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://facebook.github.io/react/docs/context.html) 特性,只需在应用外围包裹一次即可全局生效。
```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,
Input,
InputNumber,
Modal,
Pagination,
Radio,
Rate,
Row,
Select,
Space,
Steps,
Switch,
Tree,
TreeSelect,
} from 'antd';
type DirectionType = ConfigProviderProps['direction'];
const InputGroup = Input.Group;
const ButtonGroup = Button.Group;
const { TreeNode } = Tree;
const { Search } = Input;
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 }> = ({ placement }) => {
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 = (e: React.MouseEvent) => {
console.log(e);
setModalOpen(false);
};
const handleCancel = (e: React.MouseEvent) => {
console.log(e);
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 (
);
};
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
Middle
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.left = `${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` \| `middle` \| `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 |
### 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` \| `middle` \| `large` | - | 5.3.0 |
### 组件配置 {#component-config}
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| affix | 设置 Affix 组件的通用属性 | { className?: string, style?: React.CSSProperties } | - | 6.0.0 |
| alert | 设置 Alert 组件的通用属性 | { className?: string, style?: React.CSSProperties, closeIcon?: React.ReactNode, successIcon?: React.ReactNode, infoIcon?: React.ReactNode, warningIcon?: React.ReactNode, errorIcon?: React.ReactNode } | - | 5.7.0, `closeIcon`: 5.14.0, `successIcon`, `infoIcon`, `warningIcon` 和 `errorIcon`: 6.2.0 |
| anchor | 设置 Anchor 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [AnchorStyleConfig\["classNames"\]](/components/anchor-cn#semantic-dom), styles?: [AnchorStyleConfig\["styles"\]](/components/anchor-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| avatar | 设置 Avatar 组件的通用属性 | { className?: string, style?: React.CSSProperties } | - | 5.7.0 |
| badge | 设置 Badge 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [BadgeProps\["classNames"\]](/components/badge-cn#semantic-dom), styles?: [BadgeProps\["styles"\]](/components/badge-cn#semantic-dom) } | - | 5.7.0 |
| breadcrumb | 设置 Breadcrumb 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [BreadcrumbConfig\["classNames"\]](/components/breadcrumb-cn#semantic-dom), styles?: [BreadcrumbConfig\["styles"\]](/components/breadcrumb-cn#semantic-dom), separator?: ReactNode, dropdownIcon?: ReactNode } | - | 5.7.0, `classNames`, `separator` 和 `styles`: 6.0.0, `dropdownIcon`: 6.2.0 |
| button | 设置 Button 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [ButtonProps\["classNames"\]](/components/button-cn#semantic-dom), styles?: [ButtonProps\["styles"\]](/components/button-cn#semantic-dom), autoInsertSpace?: boolean, variant?: ButtonVariantType, color?: ButtonColorType, shape?: [ButtonProps\["shape"\]](/components/button#api), loadingIcon?: ReactNode } | - | 5.6.0, `autoInsertSpace`: 5.17.0, `variant` 和 `color`: 5.25.0, `shape`: 5.27.0, `loadingIcon`: 6.3.0 |
| calendar | 设置 Calendar 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [CalendarConfig\["classNames"\]](/components/calendar-cn#semantic-dom), styles?: [CalendarConfig\["styles"\]](/components/calendar-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| card | 设置 Card 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [CardProps\["classNames"\]](/components/card-cn#semantic-dom), styles?: [CardProps\["styles"\]](/components/card-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 5.14.0 |
| cardMeta | 设置 Card.Meta 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [CardMetaProps\["classNames"\]](/components/card-cn#semantic-dom), styles?: [CardMetaProps\["styles"\]](/components/card-cn#semantic-dom) } | - | 6.0.0 |
| carousel | 设置 Carousel 组件的通用属性 | { className?: string, style?: React.CSSProperties } | - | 5.7.0 |
| cascader | 设置 Cascader 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [CascaderConfig\["classNames"\]](/components/cascader#semantic-dom), styles?: [CascaderConfig\["styles"\]](/components/cascader#semantic-dom), expandIcon?: React.ReactNode, loadingIcon?: React.ReactNode } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0, `expandIcon` 和 `loadingIcon`: 6.3.0 |
| checkbox | 设置 Checkbox 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [CheckboxConfig\["classNames"\]](/components/checkbox-cn#semantic-dom), styles?: [CheckboxConfig\["styles"\]](/components/checkbox-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| collapse | 设置 Collapse 组件的通用属性 | { className?: string, style?: React.CSSProperties, expandIcon?: (props) => ReactNode, classNames?: [CollapseProps\["classNames"\]](/components/collapse-cn#semantic-dom), styles?: [CollapseProps\["styles"\]](/components/collapse-cn#semantic-dom) } | - | 5.7.0, `expandIcon`: 5.15.0, `classNames` 和 `styles`: 6.0.0 |
| colorPicker | 设置 ColorPicker 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [ColorPickerConfig\["classNames"\]](/components/color-picker-cn#semantic-dom), styles?: [ColorPickerConfig\["styles"\]](/components/color-picker-cn#semantic-dom) } | - | 5.7.0 |
| datePicker | 设置 DatePicker 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [DatePickerConfig\["classNames"\]](/components/date-picker-cn#semantic-dom), styles?: [DatePickerConfig\["styles"\]](/components/date-picker-cn#semantic-dom), suffixIcon?: React.ReactNode } | - | 5.7.0, `suffixIcon`: 6.3.0 |
| rangePicker | 设置 RangePicker 组件的通用属性 | { className?: string, style?: React.CSSProperties, separator?: React.ReactNode } | - | 5.11.0, `separator`: 6.3.0 |
| descriptions | 设置 Descriptions 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [DescriptionsProps\["classNames"\]](/components/descriptions-cn#semantic-dom), styles?: [DescriptionsProps\["styles"\]](/components/descriptions-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 5.23.0 |
| divider | 设置 Divider 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [DividerProps\["classNames"\]](/components/divider-cn#semantic-dom), styles?: [DividerProps\["styles"\]](/components/divider-cn#semantic-dom) } | - | |
| drawer | 设置 Drawer 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [DrawerProps\["classNames"\]](/components/drawer-cn#semantic-dom), styles?: [DrawerProps\["styles"\]](/components/drawer-cn#semantic-dom), closeIcon?: ReactNode, closable?: [DrawerProps\["closable"\]](/components/drawer-cn#api)} | - | 5.7.0, `classNames` 和 `styles`: 5.10.0, `closeIcon`: 5.14.0 |
| dropdown | 设置 Dropdown 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [DropdownConfig\["classNames"\]](/components/dropdown-cn#semantic-dom), styles?: [DropdownConfig\["styles"\]](/components/dropdown-cn#semantic-dom) } | - | |
| empty | 设置 Empty 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[EmptyProps\["classNames"\]](/components/empty-cn#api), styles?: [EmptyProps\["styles"\]](/components/empty-cn#api), image?: ReactNode } | - | 5.7.0, `classNames` 和 `styles`: 5.23.0, `image`: 5.27.0 |
| flex | 设置 Flex 组件的通用属性 | { className?: string, style?: React.CSSProperties, vertical?: boolean } | - | 5.10.0 |
| floatButton | 设置 FloatButton 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [FloatButtonProps\["classNames"\]](/components/float-button-cn#semantic-dom), styles?: [FloatButtonProps\["styles"\]](/components/float-button-cn#semantic-dom), backTopIcon?: React.ReactNode } | - | |
| floatButtonGroup | 设置 FloatButton.Group 组件的通用属性 | { closeIcon?: React.ReactNode, className?: string, style?: React.CSSProperties, classNames?: [FloatButtonProps\["classNames"\]](/components/float-button-cn#semantic-dom), styles?: [FloatButtonProps\["styles"\]](/components/float-button-cn#semantic-dom) } | - | |
| form | 设置 Form 组件的通用属性 | { className?: string, style?: React.CSSProperties, validateMessages?: [ValidateMessages](/components/form-cn#validatemessages), requiredMark?: boolean \| `optional`, colon?: boolean, scrollToFirstError?: boolean \| [Options](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options), classNames?:[FormConfig\["classNames"\]](/components/form-cn#semantic-dom), styles?: [FormConfig\["styles"\]](/components/form-cn#semantic-dom), tooltip?: [TooltipProps](/components/tooltip-cn#api) & { icon?: ReactNode } } | - | `requiredMark`: 4.8.0; `colon`: 4.18.0; `scrollToFirstError`: 5.2.0; `className` 和 `style`: 5.7.0; `tooltip`: 6.3.0 |
| image | 设置 Image 组件的通用属性 | { className?: string, style?: React.CSSProperties, preview?: { closeIcon?: React.ReactNode, classNames?:[ImageConfig\["classNames"\]](/components/image-cn#semantic-dom), styles?: [ImageConfig\["styles"\]](/components/image-cn#semantic-dom) }, fallback?: string } | - | 5.7.0, `closeIcon`: 5.14.0, `classNames` 和 `styles`: 6.0.0 |
| input | 设置 Input 组件的通用属性 | { autoComplete?: string, className?: string, style?: React.CSSProperties,classNames?:[InputConfig\["classNames"\]](/components/input-cn#semantic-input), styles?: [InputConfig\["styles"\]](/components/input-cn#semantic-input), allowClear?: boolean \| { clearIcon?: ReactNode } } | - | 5.7.0, `allowClear`: 5.15.0 |
| inputNumber | 设置 Input 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [InputNumberConfig\["classNames"\]](/components/input-number-cn#semantic-dom), styles?: [InputNumberConfig\["styles"\]](/components/input-number-cn#semantic-dom) } | - | |
| otp | 设置 OTP 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [OTPConfig\["classNames"\]](/components/input-cn#semantic-otp), styles?: [OTPConfig\["styles"\]](/components/input-cn#semantic-otp) } | - | |
| inputSearch | 设置 Search 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [InputSearchConfig\["classNames"\]](/components/input-cn#semantic-search), styles?: [InputSearchConfig\["styles"\]](/components/input-cn#semantic-search) } | - | |
| textArea | 设置 TextArea 组件的通用属性 | { autoComplete?: string, className?: string, style?: React.CSSProperties,classNames?:[TextAreaConfig\["classNames"\]](/components/input-cn#semantic-textarea), styles?: [TextAreaConfig\["styles"\]](/components/input-cn#semantic-textarea), allowClear?: boolean \| { clearIcon?: ReactNode } } | - | 5.15.0 |
| layout | 设置 Layout 组件的通用属性 | { className?: string, style?: React.CSSProperties } | - | 5.7.0 |
| list | 设置 List 组件的通用属性 | { className?: string, style?: React.CSSProperties, item?:{ classNames: [ListItemProps\["classNames"\]](/components/list-cn#listitem), styles: [ListItemProps\["styles"\]](/components/list-cn#listitem) } } | - | 5.7.0 |
| masonry | 设置 Masonry 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [MasonryProps\["classNames"\]](/components/masonry#semantic-dom), styles?: [MasonryProps\["styles"\]](/components/masonry#semantic-dom) } | - | |
| menu | 设置 Menu 组件的通用属性 | { className?: string, style?: React.CSSProperties, expandIcon?: ReactNode \| props => ReactNode } | - | 5.7.0, `expandIcon`: 5.15.0 |
| mentions | 设置 Mentions 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[MentionsConfig\["classNames"\]](/components/mentions-cn#semantic-dom), styles?: [MentionsConfig\["styles"\]](/components/mentions-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| message | 设置 Message 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [MessageConfig\["classNames"\]](/components/message-cn#semantic-dom), styles?: [MessageConfig\["styles"\]](/components/message-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| modal | 设置 Modal 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [ModalProps\["classNames"\]](/components/modal-cn#semantic-dom), styles?: [ModalProps\["styles"\]](/components/modal-cn#semantic-dom), closeIcon?: React.ReactNode } | - | 5.7.0, `classNames` 和 `styles`: 5.10.0, `closeIcon`: 5.14.0 |
| notification | 设置 Notification 组件的通用属性 | { className?: string, style?: React.CSSProperties, closeIcon?: React.ReactNode, classNames?: [NotificationConfig\["classNames"\]](/components/notification-cn#semantic-dom), styles?: [NotificationConfig\["styles"\]](/components/notification-cn#semantic-dom) } | - | 5.7.0, `closeIcon`: 5.14.0, `classNames` 和 `styles`: 6.0.0 |
| pagination | 设置 Pagination 组件的通用属性 | { showSizeChanger?: boolean, totalBoundaryShowSizeChanger?: number, className?: string, style?: React.CSSProperties,classNames?:[PaginationConfig\["classNames"\]](/components/pagination-cn#semantic-dom), styles?: [PaginationConfig\["styles"\]](/components/pagination-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| progress | 设置 Progress 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [ProgressConfig\["classNames"\]](/components/progress#semantic-dom), styles?: [ProgressConfig\["styles"\]](/components/progress#semantic-dom) } | - | |
| radio | 设置 Radio 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [RadioConfig\["classNames"\]](/components/radio-cn#semantic-dom), styles?: [RadioConfig\["styles"\]](/components/radio-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| rate | 设置 Rate 组件的通用属性 | { className?: string, style?: React.CSSProperties } | - | 5.7.0 |
| result | 设置 Result 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [ResultProps\["classNames"\]](/components/result-cn#semantic-dom), styles?: [ResultProps\["styles"\]](/components/result-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| ribbon | 设置 Ribbon 组件的通用属性 | { className?: string, style?: React.CSSProperties, , classNames?: [RibbonProps\["classNames"\]](/components/badge-cn#semantic-dom), styles?: [RibbonProps\["styles"\]](/components/badge-cn#semantic-dom) } | - | 6.0.0 |
| skeleton | 设置 Skeleton 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [SkeletonProps\["classNames"\]](/components/skeleton-cn#semantic-dom), styles?: [SkeletonProps\["styles"\]](/components/skeleton-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| segmented | 设置 Segmented 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [SegmentedProps\["classNames"\]](/components/segmented-cn#semantic-dom), styles?: [SegmentedProps\["styles"\]](/components/segmented-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| select | 设置 Select 组件的通用属性 | { className?: string, showSearch?: boolean, style?: React.CSSProperties, classNames?: [SelectConfig\["classNames"\]](/components/select-cn#semantic-dom), styles?: [SelectConfig\["styles"\]](/components/select-cn#semantic-dom) } | - | 5.7.0,`classNames` 和 `styles`: 6.0.0 |
| slider | 设置 Slider 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [SliderProps\["classNames"\]](/components/slider-cn#semantic-dom), styles?: [SliderProps\["styles"\]](/components/slider-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 5.23.0 |
| switch | 设置 Switch 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [SwitchStyleConfig\["classNames"\]](/components/switch-cn#semantic-dom), styles?: [SwitchStyleConfig\["styles"\]](/components/switch-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| space | 设置 Space 的通用属性,参考 [Space](/components/space-cn) | { size: `small` \| `middle` \| `large` \| `number`, className?: string, style?: React.CSSProperties, classNames?: [SpaceProps\["classNames"\]](/components/space-cn#semantic-dom), styles?: [SpaceProps\["styles"\]](/components/space-cn#semantic-dom) } | - | 5.6.0 |
| splitter | 设置 Splitter 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[Splitter\["classNames"\]](/components/splitter-cn#semantic-dom), styles?: [Splitter\["styles"\]](/components/splitter-cn#semantic-dom) } | - | 5.21.0 |
| spin | 设置 Spin 组件的通用属性 | { className?: string, style?: React.CSSProperties, indicator?: React.ReactElement, classNames?:[SpinConfig\["classNames"\]](/components/spin-cn#semantic-dom), styles?: [SpinConfig\["styles"\]](/components/spin-cn#semantic-dom) } | - | 5.7.0, `indicator`: 5.20.0, `classNames` 和 `styles`: 6.0.0 |
| statistic | 设置 Statistic 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [StatisticProps\["classNames"\]](/components/statistic-cn#semantic-dom), styles?: [StatisticProps\["styles"\]](/components/statistic-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| steps | 设置 Steps 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[StepsConfig\["classNames"\]](/components/steps#semantic-dom), styles?: [StepsConfig\["styles"\]](/components/steps#semantic-dom) } | - | |
| table | 设置 Table 组件的通用属性 | { className?: string, style?: React.CSSProperties, expandable?: { expandIcon?: props => React.ReactNode }, rowKey?: [TableProps\["rowKey"\]](/components/table-cn#api), scroll?: [TableProps\["scroll"\]](/components/table-cn#api), classNames?: [TableProps\["classNames"\]](/components/table-cn#semantic-dom), styles?: [TableProps\["styles"\]](/components/table-cn#semantic-dom) } | - | `scroll`: 6.2.0 |
| tabs | 设置 Tabs 组件的通用属性 | { className?: string, style?: React.CSSProperties, indicator?: { size?: GetIndicatorSize, align?: `start` \| `center` \| `end` }, moreIcon?: ReactNode, addIcon?: ReactNode, removeIcon?: ReactNode, classNames?: [TabsConfig\["classNames"\]](/components/tabs-cn#semantic-dom), styles?: [TabsConfig\["styles"\]](/components/tabs-cn#semantic-dom) } | - | 5.7.0, `moreIcon` and `addIcon`: 5.14.0, `removeIcon`: 5.15.0, `classNames` 和 `styles`: 6.0.0 |
| tag | 设置 Tag 组件的通用属性 | { className?: string, style?: React.CSSProperties, closeIcon?: React.ReactNode, classNames?: [TagProps\["classNames"\]](/components/tag-cn#semantic-dom), styles?: [TagProps\["styles"\]](/components/tag-cn#semantic-dom) } | - | 5.7.0, closeIcon: 5.14.0, `classNames` 和 `styles`: 6.0.0 |
| timeline | 设置 Timeline 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [TimelineConfig\["classNames"\]](/components/timeline-cn#semantic-dom), styles?: [TimelineConfig\["styles"\]](/components/timeline-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| timePicker | 设置 TimePicker 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [TimePickerConfig\["classNames"\]](/components/time-picker-cn#semantic-dom), styles?: [TimePickerConfig\["styles"\]](/components/time-picker-cn#semantic-dom), suffixIcon?: React.ReactNode } | - | 5.7.0, `suffixIcon`: 6.3.0 |
| tour | 设置 Tour 组件的通用属性 | { closeIcon?: React.ReactNode, className?: string, style?: React.CSSProperties, classNames?: [TourProps\["classNames"\]](/components/tour-cn#semantic-dom), styles?: [TourProps\["styles"\]](/components/tour-cn#semantic-dom) } | - | 5.14.0, `classNames`、`styles`、`className`、`style`: 6.0.0 |
| tooltip | 设置 Tooltip 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[Tooltip\["classNames"\]](/components/tooltip-cn#semantic-dom), styles?: [Tooltip\["styles"\]](/components/tooltip-cn#semantic-dom), arrow: boolean \| { pointAtCenter: boolean }, unique?: boolean, trigger?: [Tooltip\["trigger"\]](/components/tooltip-cn#api)} | - | `trigger`: 6.1.0 |
| popover | 设置 Popover 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[Popover\["classNames"\]](/components/popover-cn#semantic-dom), styles?: [Popover\["styles"\]](/components/popover-cn#semantic-dom), arrow: boolean \| { pointAtCenter: boolean }, trigger?: [Popover\["trigger"\]](/components/popover-cn#api)} | - | 5.23.0, `arrow`: 6.0.0, `trigger`: 6.1.0 |
| popconfirm | 设置 Popconfirm 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[Popconfirm\["classNames"\]](/components/popconfirm-cn#semantic-dom), styles?: [Popconfirm\["styles"\]](/components/popconfirm-cn#semantic-dom), arrow: boolean \| { pointAtCenter: boolean }, trigger?: [Popconfirm\["trigger"\]](/components/popconfirm-cn#api)} | - | 5.23.0, `arrow`: 6.0.0, `trigger`: 6.1.0 |
| qrcode | 设置 QRCode 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[QRCode\["classNames"\]](/components/qr-code-cn#semantic-dom), styles?: [QRCode\["styles"\]](/components/qr-code-cn#semantic-dom) } | - | |
| transfer | 设置 Transfer 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [TransferConfig\["classNames"\]](/components/transfer-cn#semantic-dom), styles?: [TransferConfig\["styles"\]](/components/transfer-cn#semantic-dom), selectionsIcon?: React.ReactNode } | - | |
| tree | 设置 Tree 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [TreeConfig\["classNames"\]](/components/tree-cn#semantic-dom), styles?: [TreeConfig\["styles"\]](/components/tree-cn#semantic-dom) } | - | 5.7.0, `classNames` 和 `styles`: 6.0.0 |
| treeSelect | 设置 TreeSelect 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?: [TreeSelectConfig\["classNames"\]](/components/tree-select-cn#semantic-dom), styles?: [TreeSelectConfig\["styles"\]](/components/tree-select-cn#semantic-dom), switcherIcon?: [TreeSelect\["switcherIcon"\]](/components/tree-select-cn#api)} | - | |
| typography | 设置 Typography 组件的通用属性 | { className?: string, style?: React.CSSProperties } | - | 5.7.0 |
| upload | 设置 Upload 组件的通用属性 | { className?: string, style?: React.CSSProperties, classNames?:[UploadConfig\["classNames"\]](/components/upload-cn#semantic-dom), styles?: [UploadConfig\["styles"\]](/components/upload-cn#semantic-dom), customRequest?: [Upload\["customRequest"\]](/components/upload#api) } | - | 5.7.0, `customRequest`: 5.27.0, `classNames` 和 `styles`: 6.0.0 |
| wave | 设置水波纹特效 | { disabled?: boolean, showEffect?: (node: HTMLElement, info: { className, token, component }) => void } | - | 5.8.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, Space } from 'antd';
const onChange: DatePickerProps['onChange'] = (date, dateString) => {
console.log(date, dateString);
};
const App: React.FC = () => (
);
export default App;
```
### 范围选择器
通过设置 `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;
```
### 三种大小
三种大小的输入框,若不设置,则为 `middle`。
```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('middle');
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
return (
Large
middle
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: `1px solid ${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 } from 'antd';
import { createStyles } from 'antd-style';
import type { Dayjs } from 'dayjs';
const useStyles = createStyles(({ token }) => ({
root: {
border: `1px solid ${token.colorPrimary}`,
width: 200,
},
}));
const stylesObject: DatePickerProps['styles'] = {
input: { fontStyle: 'italic' },
suffix: { opacity: 0.85 },
};
const stylesFn: DatePickerProps['styles'] = (info) => {
if (info.props.size === 'large') {
return {
root: { borderColor: '#722ed1' },
popup: {
container: { border: '1px solid #722ed1', borderRadius: 8 },
},
} satisfies DatePickerProps['styles'];
}
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。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| allowClear | 自定义清除按钮 | boolean \| { clearIcon?: ReactNode } | true | 5.8.0: 支持对象类型 |
| className | 选择器 className | string | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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 |
| 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` \| `middle` \| `small` | - | |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 |
| style | 自定义输入框样式 | CSSProperties | {} | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| suffixIcon | 自定义的选择框后缀图标 | ReactNode | - | |
| superNextIcon | 自定义 `>>` 切换图标 | ReactNode | - | 4.17.0 |
| superPrevIcon | 自定义 `<<` 切换图标 | ReactNode | - | 4.17.0 |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 |
| onOpenChange | 弹出日历和关闭日历的回调 | function(open) | - | |
| onPanelChange | 日历面板切换的回调 | function(value, mode) | - | |
### 共同的方法
| 名称 | 描述 | 版本 |
| ------- | -------- | ---- |
| 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 | - | |
| 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 | - | |
| 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 | - | |
| 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 | - | |
| value | 日期 | [dayjs](https://day.js.org/) | - | |
| onChange | 时间发生变化的回调,发生在用户选择时间时 | function(date: dayjs \| null, dateString: string \| null) | - | |
| showWeek | DatePicker 下展示当前周 | boolean | true | 5.14.0 |
### RangePicker
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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/)[] | - | 5.14.0 |
| defaultValue | 默认日期 | [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/)[] | - | 5.14.0 |
| presets | 预设时间范围快捷选择,自 `5.8.0` 起 value 支持函数返回值 | { label: React.ReactNode, value: (Dayjs \| (() => Dayjs))\[] }\[] | - | |
| renderExtraFooter | 在面板中添加额外的页脚 | () => React.ReactNode | - | |
| separator | 设置分隔符 | React.ReactNode | ` ` | |
| showTime | 增加时间选择功能 | Object\|boolean | [TimePicker Options](/components/time-picker-cn#api) | |
| ~~showTime.defaultValue~~ | 请使用 `showTime.defaultOpenValue` | [dayjs](https://day.js.org/)\[] | \[dayjs(), dayjs()] | 5.27.3 |
| showTime.defaultOpenValue | 设置用户选择日期时默认的时分秒,[例子](#date-picker-demo-disabled-date) | [dayjs](https://day.js.org/)\[] | \[dayjs(), dayjs()] | |
| value | 日期 | [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 | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | 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 | |
| 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<'default' | 'middle' | 'small'>('default');
const onChange = (e: RadioChangeEvent) => {
console.log('size checked', e.target.value);
setSize(e.target.value);
};
return (
default
middle
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 } 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) => {
if (info.props.size === 'default') {
return {
root: {
borderRadius: 8,
border: '1px solid #CDC1FF',
},
label: { color: '#A294F9' },
} satisfies DescriptionsProps['styles'];
}
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| bordered | 是否展示边框 | boolean | false | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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 | 设置列表的大小。可以设置为 `middle` 、`small`, 或不填(只有设置 `bordered={true}` 生效) | `default` \| `middle` \| `small` | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| 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 } from 'antd';
const classNamesObject: DividerProps['classNames'] = {
root: 'demo-divider-root',
content: 'demo-divider-content',
rail: 'demo-divider-rail',
};
const classNamesFn: DividerProps['classNames'] = (info) => {
if (info.props.titlePlacement === 'start') {
return {
root: 'demo-divider-root--start',
} satisfies DividerProps['classNames'];
}
return {
root: 'demo-divider-root--default',
} satisfies DividerProps['classNames'];
};
const stylesObject: DividerProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed' },
content: { fontStyle: 'italic' },
rail: { opacity: 0.85 },
};
const stylesFn: DividerProps['styles'] = (info) => {
if (info.props.size === 'small') {
return {
root: { opacity: 0.6, cursor: 'default' },
} satisfies DividerProps['styles'];
}
return {
root: { backgroundColor: '#fafafa', borderColor: '#d9d9d9' },
} satisfies DividerProps['styles'];
};
const App: React.FC = () => (
classNames Object
classNames Function
styles Object
styles Function
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| children | 嵌套的标题 | ReactNode | - | |
| className | 分割线样式类 | string | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| dashed | 是否虚线 | boolean | false | |
| orientation | 水平或垂直类型 | `horizontal` \| `vertical` | `horizontal` | - |
| ~~orientationMargin~~ | 标题和最近 left/right 边框之间的距离,去除了分割线,同时 `titlePlacement` 不能为 `center`。如果传入 `string` 类型的数字且不带单位,默认单位是 px | string \| number | - | |
| plain | 文字是否显示为普通正文样式 | boolean | false | 4.2.0 |
| style | 分割线样式对象 | CSSProperties | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| size | 间距大小,仅对水平布局有效 | `small` \| `middle` \| `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: `1px solid ${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';
interface DescriptionItemProps {
title: string;
content: React.ReactNode;
}
const DescriptionItem = ({ title, content }: DescriptionItemProps) => (
);
const App: React.FC = () => {
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 } 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 }) => ({
container: 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) => {
if (info.props.footer) {
return {
header: {
padding: 16,
},
body: {
padding: 16,
},
footer: {
padding: '16px 10px',
backgroundColor: '#fafafa',
},
} satisfies DrawerProps['styles'];
}
return {};
};
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)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| afterOpenChange | 切换抽屉时动画结束后的回调 | function(open) | - | |
| className | Drawer 容器外层 className 设置,如果需要设置最外层,请使用 rootClassName | string | - | |
| classNames | 用于自定义 Drawer 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| closable | 是否显示关闭按钮。可通过 `placement` 配置其位置 | boolean \| { closeIcon?: React.ReactNode; disabled?: boolean; placement?: 'start' \| 'end' } | true | placement: 5.28.0 |
| ~~destroyOnClose~~ | 关闭时销毁 Drawer 里的子元素 | boolean | false | |
| destroyOnHidden | 关闭时销毁 Drawer 里的子元素 | boolean | false | 5.25.0 |
| extra | 抽屉右上角的操作区域 | ReactNode | - | 4.17.0 |
| footer | 抽屉的页脚 | ReactNode | - | |
| forceRender | 预渲染 Drawer 内元素 | boolean | false | |
| focusable | 抽屉内焦点管理的配置 | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.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 |
| ~~maskClosable~~ | 点击蒙层是否允许关闭 | boolean | true | |
| 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 | - | |
| styles | 用于自定义 Drawer 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| 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;
```
### 弹出位置
支持 6 个弹出位置。
```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 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 onClick: MenuProps['onClick'] = ({ key }) => {
message.info(`Click on item ${key}`);
};
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 = () => (
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 handleButtonClick = (e: React.MouseEvent) => {
message.info('Click on left button.');
console.log('click left button', e);
};
const handleMenuClick: MenuProps['onClick'] = (e) => {
message.info('Click on menu item.');
console.log('click', e);
};
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 menuProps = {
items,
onClick: handleMenuClick,
};
const App: React.FC = () => (
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;
```
### 自定义语义结构的样式和类
通过 `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, MenuProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
backgroundColor: token.colorFillAlter,
border: `1px solid ${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: '#ffffff',
border: '1px solid #d9d9d9',
borderRadius: '4px',
},
item: {
padding: '8px 12px',
fontSize: '14px',
},
itemTitle: {
fontWeight: '500',
},
itemIcon: {
color: '#1890ff',
marginRight: '8px',
},
itemContent: {
backgroundColor: 'transparent',
},
};
const functionStyles: DropdownProps['styles'] = (info) => {
const { props } = info;
const isClick = props.trigger?.includes('click');
if (isClick) {
return {
root: {
borderColor: '#1890ff',
borderRadius: '8px',
},
} satisfies DropdownProps['styles'];
}
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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> | - | |
| 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 | 菜单弹出位置:`bottom` `bottomLeft` `bottomRight` `top` `topLeft` `topRight` | string | `bottomLeft` | |
| styles | 用于自定义 Dropdown 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom) , CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom) , CSSProperties> | - | |
| 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 | |
| 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 { Button, Empty, Flex } from 'antd';
import { createStaticStyles } from 'antd-style';
import type { EmptyProps } from '..';
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 }) => {
if (props.description) {
return {
root: { backgroundColor: '#e6f7ff', border: '1px solid #91d5ff' },
description: { color: '#1890ff', fontWeight: 'bold' },
image: { filter: 'hue-rotate(180deg)' },
} satisfies EmptyProps['styles'];
}
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
创建
```
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| description | 自定义描述内容 | ReactNode | - | |
| image | 设置显示图片,为 string 时表示自定义图片地址。 | ReactNode | `Empty.PRESENTED_IMAGE_DEFAULT` | |
| imageStyle | 图片样式 | CSSProperties | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
## 内置图片
- 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`、`middle`、`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', 'middle', '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)
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| vertical | flex 主轴的方向是否垂直,使用 `flex-direction: column` | boolean | `false` |
| 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` \| `middle` \| `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 { FloatButton } from 'antd';
const App: React.FC = () => (
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
Scroll to bottom
);
export default App;
```
### 徽标数
右上角附带圆形徽标数字的悬浮按钮。
```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 } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `1px solid ${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) => {
if (info.props.type === 'primary') {
return {
root: {
backgroundColor: '#171717',
},
content: {
color: '#fff',
},
} satisfies FloatButtonProps['styles'];
}
return {};
};
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| icon | 自定义图标 | ReactNode | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| 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> | - | |
| 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 |
### FloatButton.Group
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| shape | 设置包含的 FloatButton 按钮形状 | `circle` \| `square` | `circle` | |
| trigger | 触发方式(有触发方式为菜单模式) | `click` \| `hover` | - | |
| open | 受控展开,需配合 trigger 一起使用 | boolean | - | |
| closeIcon | 自定义关闭按钮 | React.ReactNode | ` ` | |
| placement | 自定义菜单弹出位置 | `top` \| `left` \| `right` \| `bottom` | `top` | 5.21.0 |
| onOpenChange | 展开收起时的回调,需配合 trigger 一起使用 | (open: boolean) => void | - | |
| onClick | 点击按钮时的回调(仅在菜单模式中有效) | (event) => void | - | 5.3.0 |
### FloatButton.BackTop
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ---------------- | ---------------------------------- | ----------------- | ------------ | ---- |
| duration | 回到顶部所需时间(ms) | number | 450 | |
| 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 | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | 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('default');
const onFormLayoutChange: FormProps['onValuesChange'] = ({ size }) => {
setComponentSize(size);
};
return (
Small
Default
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 [form] = Form.useForm();
const onFinish = () => {
message.success('Submit success!');
};
const onFinishFailed = () => {
message.error('Submit failed!');
};
const onFill = () => {
form.setFieldsValue({
url: 'https://taobao.com/',
});
};
return (
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';
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 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;
```
### 复杂的动态增减表单项
多个 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)。
**注意:** 将表单数据存储于外部容器[并非好的实践](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?: any;
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' }]);
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).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,
},
},
};
const App: React.FC = () => {
const [form] = Form.useForm();
const onFinish = (values: any) => {
console.log('Received values of form: ', values);
};
const prefixSelector = (
);
const suffixSelector = (
);
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!'));
},
}),
]}
>
{/* Demo only, real usage should wrap as custom component */}
{prefixSelector}
{/* Demo only, real usage should wrap as custom component */}
{suffixSelector}
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 } 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) => {
if (info.props.variant === 'filled') {
return {
root: {
border: '1px solid #1677FF',
},
label: {
textAlign: 'end',
color: '#1677FF',
},
content: {
paddingInlineStart: 12,
},
} satisfies FormProps['styles'];
}
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| colon | 配置 Form.Item 的 `colon` 的默认值。表示是否显示 label 后面的冒号 (只有在属性 layout 为 horizontal 时有效) | boolean | true | |
| 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` | |
| 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 |
| scrollToFirstError | 提交失败自动滚动到第一个错误字段 | boolean \| [Options](https://github.com/stipsan/scroll-into-view-if-needed/tree/ece40bd9143f48caf4b99503425ecb16b0ad8249#options) \| { focus: boolean } | false | focus: 5.24.0 |
| size | 设置字段组件的尺寸(仅限 antd 组件) | `small` \| `middle` \| `large` | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| tooltip | 配置提示属性 | [TooltipProps](/components/tooltip-cn#api) & { icon?: ReactNode } | - | 6.3.0 |
| validateMessages | 验证提示模板,说明[见下](#validatemessages) | [ValidateMessages](https://github.com/ant-design/ant-design/blob/6234509d18bac1ac60fbb3f92a5b2c6a6361295a/components/locale/en_US.ts#L88-L134) | - | |
| validateTrigger | 统一设置字段触发验证的时机 | string \| string\[] | `onChange` | 4.3.0 |
| variant | 表单内控件变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.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` 来实现。
### 为什么 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 = { background: '#0092ff', padding: '8px 0' };
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';
const App: React.FC = () => (
<>
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';
const DemoBox: React.FC> = (props) => (
{props.children}
);
const App: React.FC = () => (
<>
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';
const App: React.FC = () => (
<>
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';
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 [gutterKey, setGutterKey] = useState(1);
const [vgutterKey, setVgutterKey] = useState(1);
const [colCountKey, setColCountKey] = useState(2);
const cols = [];
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| flex | flex 布局属性 | 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}
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| className | 设置图标的样式名 | string | - | |
| rotate | 图标旋转角度(IE9 无效) | number | - | |
| spin | 是否有旋转动画 | boolean | false | |
| style | 设置图标的样式,例如 `fontSize` 和 `color` | CSSProperties | - | |
| twoToneColor | 仅适用双色图标。设置双色图标的主要颜色,支持设置十六进制颜色字符串 | string \| string[] | - | |
其中我们提供了三种主题的图标,不同主题的 Icon 组件名为图标名加主题做为后缀。
```jsx
import { StarOutlined, StarFilled, StarTwoTone } from '@ant-design/icons';
```
### 自定义 Icon {#custom-icon}
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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 的配置项如下:
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| 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` 组件的接受的属性如下:
| 字段 | 说明 | 类型 | 只读值 | 版本 |
| --------- | ----------------------- | ---------------- | -------------- | ---- |
| 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;
```
### 容错处理
加载失败显示图像占位符。
```tsx
import React from 'react';
import { Image } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 渐进加载
大图使用 placeholder 渐进加载。
```tsx
import React, { useState } from 'react';
import { Button, Image, Space } from 'antd';
const App: React.FC = () => {
const [random, setRandom] = useState(() => Date.now());
return (
}
/>
{
setRandom(Date.now());
}}
>
Reload
);
};
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';
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 [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 { 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) => {
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%)',
},
} satisfies ImageProps['styles'];
}
return {};
};
const App: React.FC = () => {
const sharedProps: ImageProps = {
src: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
width: 160,
alt: '示例图片',
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
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| alt | 图像描述 | string | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| fallback | 加载失败容错地址 | string | - | |
| height | 图像高度 | string \| number | - | |
| placeholder | 加载占位,为 `true` 时使用默认占位 | ReactNode | - | |
| preview | 预览参数,为 `false` 时禁用 | boolean \| [PreviewType](#previewtype) | true | |
| src | 图片地址 | string | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| width | 图像宽度 | string \| number | - | |
| onError | 加载错误回调 | (event: Event) => void | - | |
其他属性见 [<img>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Attributes)
### PreviewType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| actionsRender | 自定义工具栏渲染 | (originalNode: React.ReactElement, info: ToolbarRenderInfoType) => React.ReactNode | - | |
| closeIcon | 自定义关闭 Icon | React.ReactNode | - | |
| cover | 自定义预览遮罩 | React.ReactNode \| [CoverConfig](#coverconfig) | - | CoverConfig v6.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 } | true | - |
| ~~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> | - | |
| ~~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 | - | |
| 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 } | true | - |
| ~~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> | - | |
| 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 |
| zIndexPopup | 预览浮层 z-index | number | 1080 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgMask | 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer、Image 等组件的蒙层使用的是该 token | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| marginXL | 控制元素外边距,超大尺寸。 | number | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | 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 (
<>
,
Submit
,
Search on Google
,
]}
>
Some contents...
Some contents...
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 遮罩
遮罩效果。
```tsx
import React from 'react';
import { Button, Modal, Space } from 'antd';
const modalConfig = {
title: 'Title',
content: 'Some contents...',
};
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
return (
<>
{
modal.confirm({ ...modalConfig, mask: { blur: true } });
}}
>
blur
{
modal.confirm(modalConfig);
}}
>
Dimmed mask
{
modal.confirm({ ...modalConfig, mask: false });
}}
>
No mask
{contextHolder}
>
);
};
export default App;
```
### 加载中
设置对话框加载状态。
```tsx
import React from 'react';
import { Button, Modal } 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 Modal
Loading Modal}
footer={
Reload
}
loading={loading}
open={open}
onCancel={() => setOpen(false)}
>
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 自定义页脚渲染函数
自定义页脚渲染函数,支持在原有基础上进行扩展。
```tsx
import React, { useState } from 'react';
import { Button, Modal, Space } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showModal = () => {
setOpen(true);
};
const handleOk = () => {
setOpen(false);
};
const handleCancel = () => {
setOpen(false);
};
return (
<>
Open Modal
{
Modal.confirm({
title: 'Confirm',
content: 'Bla bla ...',
footer: (_, { OkBtn, CancelBtn }) => (
<>
Custom Button
>
),
});
}}
>
Open Modal Confirm
(
<>
Custom Button
>
)}
>
Some contents...
Some contents...
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 使用 hooks 获得上下文
通过 `Modal.useModal` 创建支持读取 context 的 `contextHolder`。其中仅有 hooks 方法支持 Promise `await` 操作。
```tsx
import React, { createContext } from 'react';
import { Button, Modal, Space } from 'antd';
const ReachableContext = createContext(null);
const UnreachableContext = createContext(null);
const config = {
title: 'Use Hook!',
content: (
<>
{(name) => `Reachable: ${name}!`}
{(name) => `Unreachable: ${name}!`}
>
),
};
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
return (
{
const confirmed = await modal.confirm(config);
console.log('Confirmed: ', confirmed);
}}
>
Confirm
{
modal.warning(config);
}}
>
Warning
{
modal.info(config);
}}
>
Info
{
modal.error(config);
}}
>
Error
{/* `contextHolder` should always be placed under the context you want to access */}
{contextHolder}
{/* Can not access this context since `contextHolder` is not in it */}
);
};
export default App;
```
### 国际化
设置 `okText` 与 `cancelText` 以自定义按钮文字。
```tsx
import React, { useState } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Modal, Space } from 'antd';
const LocalizedModal = () => {
const [open, setOpen] = useState(false);
const showModal = () => {
setOpen(true);
};
const hideModal = () => {
setOpen(false);
};
return (
<>
Modal
Bla bla ...
Bla bla ...
Bla bla ...
>
);
};
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
const confirm = () => {
modal.confirm({
title: 'Confirm',
icon: ,
content: 'Bla bla ...',
okText: '确认',
cancelText: '取消',
});
};
return (
<>
Confirm
{contextHolder}
>
);
};
export default App;
```
### 手动更新和移除
通过返回的 instance 手动更新和关闭对话框。
```tsx
import React from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [modal, contextHolder] = Modal.useModal();
const countDown = () => {
let secondsToGo = 5;
const instance = modal.success({
title: 'This is a notification message',
content: `This modal will be destroyed after ${secondsToGo} second.`,
});
const timer = setInterval(() => {
secondsToGo -= 1;
instance.update({
content: `This modal will be destroyed after ${secondsToGo} second.`,
});
}, 1000);
setTimeout(() => {
clearInterval(timer);
instance.destroy();
}, secondsToGo * 1000);
};
return (
<>
Open modal to close in 5s
{contextHolder}
>
);
};
export default App;
```
### 自定义位置
使用 `centered` 或类似 `style.top` 的样式来设置对话框位置。
```tsx
import React, { useState } from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [modal1Open, setModal1Open] = useState(false);
const [modal2Open, setModal2Open] = useState(false);
return (
<>
setModal1Open(true)}>
Display a modal dialog at 20px to Top
setModal1Open(false)}
onCancel={() => setModal1Open(false)}
>
some contents...
some contents...
some contents...
setModal2Open(true)}>
Vertically centered modal dialog
setModal2Open(false)}
onCancel={() => setModal2Open(false)}
>
some contents...
some contents...
some contents...
>
);
};
export default App;
```
### 自定义页脚按钮属性
传入 `okButtonProps` 和 `cancelButtonProps` 可分别自定义确定按钮和取消按钮的 props。
```tsx
import React, { useState } from 'react';
import { Button, Modal } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const showModal = () => {
setOpen(true);
};
const handleOk = (e: React.MouseEvent) => {
console.log(e);
setOpen(false);
};
const handleCancel = (e: React.MouseEvent) => {
console.log(e);
setOpen(false);
};
return (
<>
Open Modal with customized button props
Some contents...
Some contents...
Some contents...
>
);
};
export default App;
```
### 自定义渲染对话框
自定义渲染对话框, 可通过 `react-draggable` 来实现拖拽。
```tsx
import React, { useRef, useState } from 'react';
import { Button, Modal } from 'antd';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [disabled, setDisabled] = useState(true);
const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
const draggleRef = useRef(null!);
const showModal = () => {
setOpen(true);
};
const handleOk = (e: React.MouseEvent) => {
console.log(e);
setOpen(false);
};
const handleCancel = (e: React.MouseEvent) => {
console.log(e);
setOpen(false);
};
const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
const { clientWidth, clientHeight } = window.document.documentElement;
const targetRect = draggleRef.current?.getBoundingClientRect();
if (!targetRect) {
return;
}
setBounds({
left: -targetRect.left + uiData.x,
right: clientWidth - (targetRect.right - uiData.x),
top: -targetRect.top + uiData.y,
bottom: clientHeight - (targetRect.bottom - uiData.y),
});
};
return (
<>
Open Draggable Modal
{
if (disabled) {
setDisabled(false);
}
}}
onMouseOut={() => {
setDisabled(true);
}}
// fix eslintjsx-a11y/mouse-events-have-key-events
// https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
onFocus={() => {}}
onBlur={() => {}}
// end
>
Draggable Modal
}
open={open}
onOk={handleOk}
onCancel={handleCancel}
modalRender={(modal) => (
onStart(event, uiData)}
>
{modal}
)}
>
Just don't learn physics at school and your life will be full of magic and miracles.
Day before yesterday I saw a rabbit, and yesterday a deer, and today, you.
>
);
};
export default App;
```
### 自定义模态的宽度
使用 `width` 来设置模态对话框的宽度。
```tsx
import React, { useState } from 'react';
import { Button, Flex, Modal } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [openResponsive, setOpenResponsive] = useState(false);
return (
{/* Basic */}
setOpen(true)}>
Open Modal of 1000px width
setOpen(false)}
onCancel={() => setOpen(false)}
width={1000}
>
some contents...
some contents...
some contents...
{/* Responsive */}
setOpenResponsive(true)}>
Open Modal of responsive width
setOpenResponsive(false)}
onCancel={() => setOpenResponsive(false)}
width={{
xs: '90%',
sm: '80%',
md: '70%',
lg: '60%',
xl: '50%',
xxl: '40%',
}}
>
some contents...
some contents...
some contents...
);
};
export default App;
```
### 静态方法
静态方法无法消费 Context,不能动态响应 ConfigProvider 提供的各项配置,启用 `layer` 时还可能导致样式异常。请优先使用 hooks 版本或者 App 组件提供的 `modal` 实例。
```tsx
import React from 'react';
import { Button, Modal, Space } from 'antd';
const info = () => {
Modal.info({
title: 'This is a notification message',
content: (
some messages...some messages...
some messages...some messages...
),
onOk() {},
});
};
const success = () => {
Modal.success({
content: 'some messages...some messages...',
});
};
const error = () => {
Modal.error({
title: 'This is an error message',
content: 'some messages...some messages...',
});
};
const warning = () => {
Modal.warning({
title: 'This is a warning message',
content: 'some messages...some messages...',
});
};
const App: React.FC = () => (
Info
Success
Error
Warning
);
export default App;
```
### 静态确认对话框
使用 `confirm()` 可以快捷地弹出确认框。onCancel/onOk 返回 promise 可以延迟关闭。
```tsx
import React from 'react';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { Button, Modal, Space } from 'antd';
const { confirm } = Modal;
const showConfirm = () => {
confirm({
title: 'Do you want to delete these items?',
icon: ,
content: 'Some descriptions',
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
};
const showPromiseConfirm = () => {
confirm({
title: 'Do you want to delete these items?',
icon: ,
content: 'When clicked the OK button, this dialog will be closed after 1 second',
onOk() {
return new Promise((resolve, reject) => {
setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
}).catch(() => console.log('Oops errors!'));
},
onCancel() {},
});
};
const showDeleteConfirm = () => {
confirm({
title: 'Are you sure delete this task?',
icon: ,
content: 'Some descriptions',
okText: 'Yes',
okType: 'danger',
cancelText: 'No',
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
};
const showPropsConfirm = () => {
confirm({
title: 'Are you sure delete this task?',
icon: ,
content: 'Some descriptions',
okText: 'Yes',
okType: 'danger',
okButtonProps: {
disabled: true,
},
cancelText: 'No',
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
};
const App: React.FC = () => (
Confirm
With promise
Delete
With extra props
);
export default App;
```
### 销毁确认对话框
使用 `Modal.destroyAll()` 可以销毁弹出的确认窗。通常用于路由监听当中,处理路由前进、后退不能销毁确认对话框的问题。
```tsx
import React from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Modal } from 'antd';
const { confirm } = Modal;
const destroyAll = () => {
Modal.destroyAll();
};
const showConfirm = () => {
for (let i = 0; i < 3; i += 1) {
setTimeout(() => {
confirm({
icon: ,
content: Click to destroy all ,
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
}, i * 500);
}
};
const App: React.FC = () => Confirm ;
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象或者函数可以自定义 Modal 组件的 [语义化结构](#semantic-dom) 样式。
```tsx
import React, { useState } from 'react';
import { Button, Flex, Modal } from 'antd';
import type { ModalProps } 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 }) => ({
container: css`
border-radius: 10px;
padding: 10px;
`,
}));
const styles: ModalProps['styles'] = {
mask: {
backgroundImage: `linear-gradient(to top, #18181b 0, rgba(21, 21, 22, 0.2) 100%)`,
},
};
const stylesFn: ModalProps['styles'] = (info) => {
if (info.props.footer) {
return {
container: {
borderRadius: 14,
border: '1px solid #ccc',
padding: 0,
overflow: 'hidden',
},
header: {
padding: 16,
},
body: {
padding: 16,
},
footer: {
padding: '16px 10px',
backgroundColor: '#fafafa',
},
} satisfies ModalProps['styles'];
}
return {};
};
const App: React.FC = () => {
const [modalOpen, setModalOpen] = useState(false);
const [modalFnOpen, setModalFnOpen] = useState(false);
const sharedProps: ModalProps = {
centered: true,
classNames,
};
const footer: React.ReactNode = (
<>
setModalFnOpen(false)}
styles={{ root: { borderColor: '#ccc', color: '#171717', backgroundColor: '#fff' } }}
>
Cancel
setModalOpen(true)}
>
Submit
>
);
return (
setModalOpen(true)}>Open Style Modal
setModalFnOpen(true)}>
Open Function Modal
setModalOpen(false)}
onCancel={() => setModalOpen(false)}
>
{sharedContent}
setModalFnOpen(false)}
onCancel={() => setModalFnOpen(false)}
>
{sharedContent}
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| afterClose | Modal 完全关闭后的回调 | function | - | |
| cancelButtonProps | cancel 按钮 props | [ButtonProps](/components/button-cn#api) | - | |
| cancelText | 取消按钮文字 | ReactNode | `取消` | |
| centered | 垂直居中展示 Modal | boolean | false | |
| classNames | 用于自定义 Modal 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| closable | 是否显示右上角的关闭按钮 | boolean \| [ClosableType](#closabletype) | true | - |
| closeIcon | 自定义关闭图标。5.7.0:设置为 `null` 或 `false` 时隐藏关闭按钮 | ReactNode | <CloseOutlined /> | |
| confirmLoading | 确定按钮 loading | boolean | false | |
| ~~destroyOnClose~~ | 关闭时销毁 Modal 里的子元素 | boolean | false | |
| destroyOnHidden | 关闭时销毁 Modal 里的子元素 | boolean | false | 5.25.0 |
| ~~focusTriggerAfterClose~~ | 对话框关闭后是否需要聚焦触发元素。请使用 `focusable.focusTriggerAfterClose` 替代 | boolean | true | 4.9.0 |
| footer | 底部内容,当不需要默认底部按钮时,可以设为 `footer={null}` | ReactNode \| (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode | (确定取消按钮) | renderFunction: 5.9.0 |
| forceRender | 强制渲染 Modal | boolean | false | |
| focusable | 对话框内焦点管理的配置 | `{ trap?: boolean, focusTriggerAfterClose?: boolean }` | - | 6.2.0 |
| getContainer | 指定 Modal 挂载的节点,但依旧为全屏展示,`false` 为挂载在当前位置 | HTMLElement \| () => HTMLElement \| Selectors \| false | document.body | |
| keyboard | 是否支持键盘 esc 关闭 | boolean | true | |
| mask | 遮罩效果 | boolean \| `{enabled: boolean, blur: boolean, closable?: boolean}` | true | mask.closable: 6.3.0 |
| maskClosable | 点击蒙层是否允许关闭 | boolean | true | |
| modalRender | 自定义渲染对话框 | (node: ReactNode) => ReactNode | - | 4.7.0 |
| okButtonProps | ok 按钮 props | [ButtonProps](/components/button-cn#api) | - | |
| okText | 确认按钮文字 | ReactNode | `确定` | |
| okType | 确认按钮类型 | string | `primary` | |
| style | 可用于设置浮层的样式,调整浮层位置等 | CSSProperties | - | |
| styles | 用于自定义 Modal 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| loading | 显示骨架屏 | boolean | | 5.18.0 |
| title | 标题 | ReactNode | - | |
| open | 对话框是否可见 | boolean | - | |
| width | 宽度 | string \| number \| [Breakpoint](/components/grid-cn#col) | 520 | Breakpoint: 5.23.0 |
| wrapClassName | 对话框外层容器的类名 | string | - | |
| zIndex | 设置 Modal 的 `z-index` | number | 1000 | |
| onCancel | 点击遮罩层或右上角叉或取消按钮的回调 | function(e) | - | |
| onOk | 点击确定回调 | function(e) | - | |
| afterOpenChange | 打开和关闭 Modal 时动画结束后的回调 | (open: boolean) => void | - | 5.4.0 |
#### 注意
- ` ` 默认关闭后状态不会自动清空,如果希望每次打开都是新内容,请设置 `destroyOnHidden`。
- ` ` 和 Form 一起配合使用时,设置 `destroyOnHidden` 也不会在 Modal 关闭时销毁表单字段数据,需要设置 ` `。
- `Modal.method()` RTL 模式仅支持 hooks 用法。
### Modal.method()
包括:
- `Modal.info`
- `Modal.success`
- `Modal.error`
- `Modal.warning`
- `Modal.confirm`
以上均为一个函数,参数为 object,具体属性如下:
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| afterClose | Modal 完全关闭后的回调 | function | - | 4.9.0 |
| ~~autoFocusButton~~ | 指定自动获得焦点的按钮。请使用 `focusable.autoFocusButton` 替代 | null \| `ok` \| `cancel` | `ok` | |
| cancelButtonProps | cancel 按钮 props | [ButtonProps](/components/button-cn#api) | - | |
| cancelText | 设置 Modal.confirm 取消按钮文字 | string | `取消` | |
| centered | 垂直居中展示 Modal | boolean | false | |
| className | 容器类名 | string | - | |
| closable | 是否显示右上角的关闭按钮 | boolean \| [ClosableType](#closabletype) | false | - |
| closeIcon | 自定义关闭图标 | ReactNode | undefined | 4.9.0 |
| content | 内容 | ReactNode | - | |
| focusable.autoFocusButton | 指定自动获得焦点的按钮 | null \| `ok` \| `cancel` | `ok` | 6.2.0 |
| footer | 底部内容,当不需要默认底部按钮时,可以设为 `footer: null` | ReactNode \| (originNode: ReactNode, extra: { OkBtn: React.FC, CancelBtn: React.FC }) => ReactNode | - | renderFunction: 5.9.0 |
| getContainer | 指定 Modal 挂载的 HTML 节点,false 为挂载在当前 dom | HTMLElement \| () => HTMLElement \| Selectors \| false | document.body | |
| icon | 自定义图标 | ReactNode | <ExclamationCircleFilled /> | |
| keyboard | 是否支持键盘 esc 关闭 | boolean | true | |
| mask | 遮罩效果 | boolean \| `{enabled?: boolean, blur?: boolean, closable?: boolean, closable?: true}` | true | |
| ~~maskClosable~~ | 点击蒙层是否允许关闭 | boolean | false | |
| okButtonProps | ok 按钮 props | [ButtonProps](/components/button-cn#api) | - | |
| okText | 确认按钮文字 | string | `确定` | |
| okType | 确认按钮类型 | string | `primary` | |
| style | 可用于设置浮层的样式,调整浮层位置等 | CSSProperties | - | |
| title | 标题 | ReactNode | - | |
| width | 宽度 | string \| number | 416 | |
| wrapClassName | 对话框外层容器的类名 | string | - | 4.18.0 |
| zIndex | 设置 Modal 的 `z-index` | number | 1000 | |
| onCancel | 点击取消回调,参数为关闭函数,若返回 promise 时 resolve 为正常关闭, reject 为不关闭 | function(close) | - | |
| onOk | 点击确定回调,参数为关闭函数,若返回 promise 时 resolve 为正常关闭, reject 为不关闭 | function(close) | - | |
以上函数调用后,会返回一个引用,可以通过该引用更新和关闭弹窗。
### ClosableType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| ---------- | ---------------------- | --------- | --------- | ---- |
| afterClose | Modal 完全关闭后的回调 | function | - | - |
| closeIcon | 自定义关闭图标 | ReactNode | undefined | - |
| disabled | 关闭图标是否禁用 | boolean | false | - |
| onClose | 弹窗关闭即时调用 | Function | undefined | - |
```jsx
const modal = Modal.info();
modal.update({
title: '修改的标题',
content: '修改的内容',
});
// 在 4.8.0 或更高版本中,可以通过传入函数的方式更新弹窗
modal.update((prevConfig) => ({
...prevConfig,
title: `${prevConfig.title}(新)`,
}));
modal.destroy();
```
- `Modal.destroyAll`
使用 `Modal.destroyAll()` 可以销毁弹出的确认窗(即上述的 `Modal.info`、`Modal.success`、`Modal.error`、`Modal.warning`、`Modal.confirm`)。通常用于路由监听当中,处理路由前进、后退不能销毁确认对话框的问题,而不用各处去使用实例的返回值进行关闭(`modal.destroy()` 适用于主动关闭,而不是路由这样被动关闭)
```jsx
import { browserHistory } from 'react-router';
// router change
browserHistory.listen(() => {
Modal.destroyAll();
});
```
### Modal.useModal()
当你需要使用 Context 时,可以通过 `Modal.useModal` 创建一个 `contextHolder` 插入子节点中。通过 hooks 创建的临时 Modal 将会得到 `contextHolder` 所在位置的所有上下文。创建的 `modal` 对象拥有与 [`Modal.method`](#modalmethod) 相同的创建通知方法。
```jsx
const [modal, contextHolder] = Modal.useModal();
React.useEffect(() => {
modal.confirm({
// ...
});
}, []);
return {contextHolder}
;
```
`modal.confirm` 返回方法:
- `destroy`:销毁当前窗口
- `update`:更新当前窗口
- `then`:Promise 链式调用,支持 `await` 操作。该方法为 Hooks 仅有
```tsx
//点击 `onOk` 时返回 `true`,点击 `onCancel` 时返回 `false`
const confirmed = await modal.confirm({ ... });
```
## Semantic DOM
https://ant.design/components/modal-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Modal)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| contentBg | 内容区域背景色 | string | #ffffff |
| footerBg | 底部区域背景色 | string | transparent |
| headerBg | 顶部背景色 | string | transparent |
| titleColor | 标题字体颜色 | string | rgba(0,0,0,0.88) |
| titleFontSize | 标题字体大小 | number | 16 |
| titleLineHeight | 标题行高 | string \| number | 1.5 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| boxShadow | 控制元素阴影样式。 | string | |
| colorBgMask | 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer、Image 等组件的蒙层使用的是该 token | string | |
| colorBgTextActive | 控制文本在激活状态下的背景色。 | string | |
| colorBgTextHover | 控制文本在悬停状态下的背景色。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeHeading5 | h5 标签使用的字号 | number | |
| fontSizeLG | 大号字体大小 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightHeading5 | h5 标签所使用的行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| motionEaseOutCirc | 预设动效曲率 | string | |
| padding | 控制元素的内间距。 | number | |
| screenLGMin | 控制大屏幕的最小宽度。 | number | |
| screenMDMin | 控制中等屏幕的最小宽度。 | number | |
| screenSMMax | 控制小屏幕的最大宽度。 | number | |
| screenSMMin | 控制小屏幕的最小宽度。 | number | |
| screenXLMin | 控制超大屏幕的最小宽度。 | number | |
| screenXSMin | 控制超小屏幕的最小宽度。 | number | |
| screenXXLMin | 控制超超大屏幕的最小宽度。 | number | |
| zIndexPopupBase | 浮层类组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 FloatButton、 Affix、Modal 等 | number | |
## FAQ
### 为什么 Modal 关闭时,内容不会更新? {#faq-content-not-update}
Modal 在关闭时会将内容进行 memo 从而避免关闭过程中的内容跳跃。也因此如果你在配合使用 Form 有关闭时重置 `initialValues` 的操作,请通过在 effect 中调用 `resetFields` 来重置。
### 为什么 Modal 方法不能获取 context、redux、的内容和 ConfigProvider `locale/prefixCls/theme` 等配置? {#faq-context-redux}
直接调用 Modal 方法,antd 会通过 `ReactDOM.render` 动态创建新的 React 实体。其 context 与当前代码所在 context 并不相同,因而无法获取 context 信息。
当你需要 context 信息(例如 ConfigProvider 配置的内容)时,可以通过 `Modal.useModal` 方法会返回 `modal` 实体以及 `contextHolder` 节点。将其插入到你需要获取 context 位置即可:
```tsx
const [modal, contextHolder] = Modal.useModal();
return (
{/* contextHolder 在 Context1 内,它可以获得 Context1 的 context */}
{contextHolder}
{/* contextHolder 在 Context2 外,因而不会获得 Context2 的 context */}
);
```
**异同**:通过 hooks 创建的 `contextHolder` 必须插入到子元素节点中才会生效,当你不需要上下文信息时请直接调用。
> 可通过 [App 包裹组件](/components/app-cn) 简化 `useModal` 等方法需要手动植入 contextHolder 的问题。
### 静态方法如何设置 prefixCls ? {#faq-set-prefix-cls}
你可以通过 [`ConfigProvider.config`](/components/config-provider-cn#configproviderconfig-4130) 进行设置。
---
## notification-cn
Source: https://ant.design/components/notification-cn.md
---
category: Components
group: 反馈
noinstant: true
title: Notification
subtitle: 通知提醒框
description: 全局展示通知提醒信息。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*cRmqTY4nKPEAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*W3RmSov-xVMAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
在系统四个角显示通知提醒信息。经常用于以下情况:
- 较为复杂的通知内容。
- 带有交互的通知,给出用户下一步的行动点。
- 系统主动推送。
## 代码演示 {#examples}
### Hooks 调用(推荐)
通过 `notification.useNotification` 创建支持读取 context 的 `contextHolder`。请注意,我们推荐通过顶层注册的方式代替 `notification` 静态方法,因为静态方法无法消费上下文,因而 ConfigProvider 的数据也不会生效。
```tsx
import React, { useMemo } from 'react';
import {
RadiusBottomleftOutlined,
RadiusBottomrightOutlined,
RadiusUpleftOutlined,
RadiusUprightOutlined,
} from '@ant-design/icons';
import { Button, Divider, notification, Space } from 'antd';
import type { NotificationArgsProps } from 'antd';
type NotificationPlacement = NotificationArgsProps['placement'];
const Context = React.createContext({ name: 'Default' });
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = (placement: NotificationPlacement) => {
api.info({
title: `Notification ${placement}`,
description: {({ name }) => `Hello, ${name}!`} ,
placement,
});
};
const contextValue = useMemo(() => ({ name: 'Ant Design' }), []);
return (
{contextHolder}
openNotification('topLeft')}
icon={ }
>
topLeft
openNotification('topRight')}
icon={ }
>
topRight
openNotification('bottomLeft')}
icon={ }
>
bottomLeft
openNotification('bottomRight')}
icon={ }
>
bottomRight
);
};
export default App;
```
### 自动关闭的延时
自定义通知框自动关闭的延时,默认 `4.5s`,取消自动关闭只要将该值设为 `0` 即可。
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
title: 'Notification Title',
description:
'I will never close automatically. This is a purposely very very long description that has many many characters and words.',
duration: 0,
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### 带有图标的通知提醒框
通知提醒框左侧有图标。
```tsx
import React from 'react';
import { Button, Flex, notification } from 'antd';
type NotificationType = 'success' | 'info' | 'warning' | 'error';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotificationWithIcon = (type: NotificationType) => {
api[type]({
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.',
});
};
return (
<>
{contextHolder}
openNotificationWithIcon('success')}
>
Success
openNotificationWithIcon('info')}>
Info
openNotificationWithIcon('warning')}
>
Warning
openNotificationWithIcon('error')}>
Error
>
);
};
export default App;
```
### 自定义按钮
自定义关闭按钮的样式和文字。
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
const close = () => {
console.log(
'Notification was closed. Either the close button was clicked or duration time elapsed.',
);
};
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
const key = `open${Date.now()}`;
const btn = (
api.destroy()}>
Destroy All
api.destroy(key)}>
Confirm
);
api.open({
title: 'Notification Title',
description:
'A function will be be called after the notification is closed (automatically after the "duration" time of manually).',
btn,
key,
onClose: close,
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### 自定义图标
图标可以被自定义。
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { Button, notification } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.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.',
icon: ,
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### 位置
使用 `placement` 可以配置通知从上面、下面、左上角、右上角、左下角、右下角弹出。
```tsx
import React from 'react';
import {
BorderBottomOutlined,
BorderTopOutlined,
RadiusBottomleftOutlined,
RadiusBottomrightOutlined,
RadiusUpleftOutlined,
RadiusUprightOutlined,
} from '@ant-design/icons';
import { Button, Divider, notification, Space } from 'antd';
import type { NotificationArgsProps } from 'antd';
type NotificationPlacement = NotificationArgsProps['placement'];
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = (placement: NotificationPlacement) => {
api.info({
title: `Notification ${placement}`,
description:
'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
placement,
});
};
return (
<>
{contextHolder}
openNotification('top')} icon={ }>
top
openNotification('bottom')}
icon={ }
>
bottom
openNotification('topLeft')}
icon={ }
>
topLeft
openNotification('topRight')}
icon={ }
>
topRight
openNotification('bottomLeft')}
icon={ }
>
bottomLeft
openNotification('bottomRight')}
icon={ }
>
bottomRight
>
);
};
export default App;
```
### 自定义样式
使用 style 和 className 来定义样式。
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.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.',
className: 'custom-class',
style: {
width: 600,
},
});
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### 更新消息内容
可以通过唯一的 key 来更新内容。
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const key = 'updatable';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
key,
title: 'Notification Title',
description: 'description.',
});
setTimeout(() => {
api.open({
key,
title: 'New Title',
description: 'New description.',
});
}, 1000);
};
return (
<>
{contextHolder}
Open the notification box
>
);
};
export default App;
```
### 堆叠
堆叠配置,默认开启。超过 3 个以上的消息会被自动收起,可以通过 `threshold` 来设置不会被收起的最大数量。
```tsx
import React, { useMemo } from 'react';
import { Button, Divider, InputNumber, notification, Space, Switch } from 'antd';
const Context = React.createContext({ name: 'Default' });
const App: React.FC = () => {
const [enabled, setEnabled] = React.useState(true);
const [threshold, setThreshold] = React.useState(3);
const [api, contextHolder] = notification.useNotification({
stack: enabled
? {
threshold,
}
: false,
});
const openNotification = () => {
api.open({
title: 'Notification Title',
description: `${Array.from(
{ length: Math.round(Math.random() * 5) + 1 },
() => 'This is the content of the notification.',
).join('\n')}`,
duration: false,
});
};
const contextValue = useMemo(() => ({ name: 'Ant Design' }), []);
return (
{contextHolder}
Enabled:
setEnabled(v)} />
Threshold:
setThreshold(v || 0)}
/>
Open the notification box
);
};
export default App;
```
### 显示进度条
显示自动关闭通知框的进度条。
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const openNotification = (pauseOnHover: boolean) => () => {
api.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.',
showProgress: true,
pauseOnHover,
});
};
return (
<>
{contextHolder}
Pause on hover
Don't pause on hover
>
);
};
export default App;
```
### 静态方法(不推荐)
静态方法无法消费 Context,不能动态响应 ConfigProvider 提供的各项配置,启用 `layer` 时还可能导致样式异常。请优先使用 hooks 版本或者 App 组件提供的 `notification` 实例。
```tsx
import React from 'react';
import { Button, notification } from 'antd';
const openNotification = () => {
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.',
onClick: () => {
console.log('Notification Clicked!');
},
});
};
const App: React.FC = () => (
Open the notification box
);
export default App;
```
### 自定义进度条颜色
通过配置组件 token 来自定义进度条颜色。
```tsx
import React from 'react';
import { Button, ConfigProvider, notification } from 'antd';
import { createStyles } from 'antd-style';
const COLOR_BG = 'linear-gradient(135deg,#6253e1, #04befe)';
const useStyle = createStyles(({ prefixCls, css }) => ({
linearGradientButton: css`
&.${prefixCls}-btn-primary:not([disabled]):not(.${prefixCls}-btn-dangerous) {
> span {
position: relative;
}
&::before {
content: '';
background: ${COLOR_BG};
position: absolute;
inset: -1px;
opacity: 1;
transition: all 0.3s;
border-radius: inherit;
}
&:hover::before {
opacity: 0;
}
}
`,
}));
const App: React.FC = () => {
const { styles } = useStyle();
const [api, contextHolder] = notification.useNotification();
const openNotification = () => {
api.open({
title: 'Customize progress bar color',
description: 'You can use component token to customize the progress bar color',
showProgress: true,
duration: 20,
});
};
return (
{contextHolder}
Show custom progress color
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Notification 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Button, notification, Space } from 'antd';
import type { NotificationArgsProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
`,
}));
const styleFn: NotificationArgsProps['styles'] = ({ props }) => {
if (props.type === 'error') {
return {
root: {
backgroundColor: `rgba(255, 200, 200, 0.3)`,
},
} satisfies NotificationArgsProps['styles'];
}
return {};
};
const App: React.FC = () => {
const [api, contextHolder] = notification.useNotification();
const sharedProps: NotificationArgsProps = {
title: 'Notification Title',
description: 'This is a notification description.',
duration: false,
classNames: { root: classNames.root },
};
const openDefault = () => {
api.info({
...sharedProps,
styles: { root: { borderRadius: 8 } },
});
};
const openError = () => {
api.error({
...sharedProps,
type: 'error',
styles: styleFn,
});
};
return (
<>
{contextHolder}
Default Notification
Error Notification
>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
- `notification.success(config)`
- `notification.error(config)`
- `notification.info(config)`
- `notification.warning(config)`
- `notification.open(config)`
- `notification.destroy(key?: String)`
config 参数如下:
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| actions | 自定义按钮组 | ReactNode | - | 5.24.0 |
| ~~btn~~ | 自定义按钮组,请使用 `actions` 替换 | ReactNode | - | - |
| className | 自定义 CSS class | string | - | - |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| closable | 是否显示右上角的关闭按钮 | boolean \| [ClosableType](#closabletype) | true | - |
| closeIcon | 自定义关闭图标 | ReactNode | true | 5.7.0:设置为 null 或 false 时隐藏关闭按钮 |
| description | 通知提醒内容,必选 | ReactNode | - | - |
| duration | 默认 4.5 秒后自动关闭,配置为 `0 \| false` 则不会自动关闭 | number \| false | 4.5 | - |
| showProgress | 显示自动关闭通知框的进度条 | boolean | | 5.18.0 |
| pauseOnHover | 悬停时是否暂停计时器 | boolean | true | 5.18.0 |
| icon | 自定义图标 | ReactNode | - | - |
| key | 当前通知唯一标志 | string | - | - |
| title | 通知提醒标题 | ReactNode | - | 6.0.0 |
| ~~message~~ | 通知提醒标题,请使用 `title` 替换 | ReactNode | - | - |
| placement | 弹出位置,可选 `top` \| `topLeft` \| `topRight` \| `bottom` \| `bottomLeft` \| `bottomRight` | string | `topRight` | - |
| role | 供屏幕阅读器识别的通知内容语义,默认为 `alert`。此情况下屏幕阅读器会立即打断当前正在阅读的其他内容,转而阅读通知内容 | `alert \| status` | `alert` | 5.6.0 |
| style | 自定义内联样式 | [CSSProperties](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e434515761b36830c3e58a970abf5186f005adac/types/react/index.d.ts#L794) | - | - |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| onClick | 点击通知时触发的回调函数 | function | - | - |
| onClose | 当通知关闭时触发 | function | - | - |
| props | 透传至通知 `div` 上的 props 对象,支持传入 `data-*` `aria-*` 或 `role` 作为对象的属性。需要注意的是,虽然在 TypeScript 类型中声明的类型支持传入 `data-*` 作为对象的属性,但目前只允许传入 `data-testid` 作为对象的属性。 详见 https://github.com/microsoft/TypeScript/issues/28960 | Object | - | - |
- `notification.useNotification(config)`
config 参数如下:
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| bottom | 消息从底部弹出时,距离底部的位置,单位像素 | number | 24 | |
| closeIcon | 自定义关闭图标 | ReactNode | true | 5.7.0:设置为 null 或 false 时隐藏关闭按钮 |
| getContainer | 配置渲染节点的输出位置 | () => HTMLNode | () => document.body | |
| placement | 弹出位置,可选 `top` \| `topLeft` \| `topRight` \| `bottom` \| `bottomLeft` \| `bottomRight` | string | `topRight` | |
| showProgress | 显示自动关闭通知框的进度条 | boolean | | 5.18.0 |
| pauseOnHover | 悬停时是否暂停计时器 | boolean | true | 5.18.0 |
| rtl | 是否开启 RTL 模式 | boolean | false | |
| stack | 堆叠模式,超过阈值时会将所有消息收起 | boolean \| `{ threshold: number }` | `{ threshold: 3 }` | 5.10.0 |
| top | 消息从顶部弹出时,距离顶部的位置,单位像素 | number | 24 | |
| maxCount | 最大显示数,超过限制时,最早的消息会被自动关闭 | number | - | 4.17.0 |
### ClosableType
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------- | ---------------- | --------- | --------- | ---- |
| closeIcon | 自定义关闭图标 | ReactNode | undefined | - |
| onClose | 当通知关闭时触发 | function | - | - |
### 全局配置
还提供了一个全局配置方法,在调用前提前配置,全局一次生效。
`notification.config(options)`
> 当你使用 `ConfigProvider` 进行全局化配置时,系统会默认自动开启 RTL 模式。(4.3.0+)
>
> 当你想单独使用,可通过如下设置开启 RTL 模式。
```js
notification.config({
placement: 'bottomRight',
bottom: 50,
duration: 3,
rtl: true,
});
```
#### notification.config
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| bottom | 消息从底部弹出时,距离底部的位置,单位像素 | number | 24 | |
| closeIcon | 自定义关闭图标 | ReactNode | true | 5.7.0:设置为 null 或 false 时隐藏关闭按钮 |
| duration | 默认自动关闭延时,单位秒 | number | 4.5 | |
| showProgress | 显示自动关闭通知框的进度条 | boolean | | 5.18.0 |
| pauseOnHover | 悬停时是否暂停计时器 | boolean | true | 5.18.0 |
| getContainer | 配置渲染节点的输出位置,但依旧为全屏展示 | () => HTMLNode | () => document.body | |
| placement | 弹出位置,可选 `top` `topLeft` `topRight` `bottom` `bottomLeft` `bottomRight` | string | `topRight` | |
| rtl | 是否开启 RTL 模式 | boolean | false | |
| top | 消息从顶部弹出时,距离顶部的位置,单位像素 | number | 24 | |
| maxCount | 最大显示数,超过限制时,最早的消息会被自动关闭 | number | - | 4.17.0 |
## Semantic DOM
https://ant.design/components/notification-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Notification)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorErrorBg | 错误提醒框容器背景色 | string | |
| colorInfoBg | 信息提醒框容器背景色 | string | |
| colorSuccessBg | 成功提醒框容器背景色 | string | |
| colorWarningBg | 警告提醒框容器背景色 | string | |
| progressBg | 提醒框进度条背景色 | string | linear-gradient(90deg, #69b1ff, #1677ff) |
| width | 提醒框宽度 | string \| number | 384 |
| zIndexPopup | 提醒框 z-index | number | 2050 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| boxShadow | 控制元素阴影样式。 | string | |
| colorBgBlur | 控制毛玻璃容器的背景色,通常为透明色。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorBgTextActive | 控制文本在激活状态下的背景色。 | string | |
| colorBgTextHover | 控制文本在悬停状态下的背景色。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorIcon | 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 * | string | |
| colorIconHover | 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 | string | |
| colorInfo | 用于表示操作信息的 Token 序列,如 Alert 、Tag、 Progress 等组件都有用到该组梯度变量。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorSuccess | 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginLG | 控制元素外边距,大尺寸。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| paddingContentHorizontalLG | 控制内容元素水平内间距,适用于大屏幕设备。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingMD | 控制元素的中等内间距。 | number | |
## FAQ
### 为什么 notification 不能获取 context、redux 的内容和 ConfigProvider 的 `locale/prefixCls/theme` 等配置? {#faq-context-redux}
直接调用 notification 方法,antd 会通过 `ReactDOM.render` 动态创建新的 React 实体。其 context 与当前代码所在 context 并不相同,因而无法获取 context 信息。
当你需要 context 信息(例如 ConfigProvider 配置的内容)时,可以通过 `notification.useNotification` 方法会返回 `api` 实体以及 `contextHolder` 节点。将其插入到你需要获取 context 位置即可:
```tsx
const [api, contextHolder] = notification.useNotification();
return (
{/* contextHolder 在 Context1 内,它可以获得 Context1 的 context */}
{contextHolder}
{/* contextHolder 在 Context2 外,因而不会获得 Context2 的 context */}
);
```
**异同**:通过 hooks 创建的 `contextHolder` 必须插入到子元素节点中才会生效,当你不需要上下文信息时请直接调用。
> 可通过 [App 包裹组件](/components/app-cn) 简化 `useNotification` 等方法需要手动植入 contextHolder 的问题。
### 静态方法如何设置 prefixCls ? {#faq-set-prefix-cls}
你可以通过 [`ConfigProvider.config`](/components/config-provider-cn#configproviderconfig-4130) 进行设置。
---
## overview-cn
Source: https://ant.design/components/overview-cn.md
---
category: Components
title: 组件总览
showImport: false
---
`antd` 为 Web 应用提供了丰富的基础 UI 组件,我们还将持续探索企业级应用的最佳 UI 实践。除了官方组件,我们也提供了[社区精选组件](/docs/react/recommendation-cn)作为必要的补充,另外如果您是内网用户,欢迎尝试使用 [TechUI](https://techui.alipay.com)。
---
## pagination-cn
Source: https://ant.design/components/pagination-cn.md
---
category: Components
group: 导航
title: Pagination
subtitle: 分页
description: 分页器用于分隔长列表,每次只加载一个页面。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*8y_iTJGY_aUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*WM86SrBC8TsAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 当加载/渲染所有数据将花费很多时间时;
- 可切换页码浏览数据。
## 代码演示 {#examples}
### 基本
基础分页。
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 方向
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 更多
更多分页。
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 改变
改变每页显示条目数。
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
console.log(current, pageSize);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### 跳转
快速跳转到某一页。
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const onChange: PaginationProps['onChange'] = (pageNumber) => {
console.log('Page: ', pageNumber);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### 尺寸
小尺寸和大尺寸的分页控件。
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Divider, Flex, Pagination } from 'antd';
const showTotal: PaginationProps['showTotal'] = (total) => `Total ${total} items`;
const App: React.FC = () => (
Small
Large
);
export default App;
```
### 简洁
简单的翻页。
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 受控
受控制的页码。
```tsx
import React, { useState } from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(3);
const onChange: PaginationProps['onChange'] = (page) => {
console.log(page);
setCurrent(page);
};
return ;
};
export default App;
```
### 总数
通过设置 `showTotal` 展示总共有多少数据。
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
<>
`Total ${total} items`}
defaultPageSize={20}
defaultCurrent={1}
/>
`${range[0]}-${range[1]} of ${total} items`}
defaultPageSize={20}
defaultCurrent={1}
/>
>
);
export default App;
```
### 全部展示
展示所有配置选项。
```tsx
import React from 'react';
import { Pagination } from 'antd';
const App: React.FC = () => (
`Total ${total} items`}
/>
);
export default App;
```
### 上一步和下一步
修改上一步和下一步为文字链接。
```tsx
import React from 'react';
import type { PaginationProps } from 'antd';
import { Pagination } from 'antd';
const itemRender: PaginationProps['itemRender'] = (_, type, originalElement) => {
if (type === 'prev') {
return Previous ;
}
if (type === 'next') {
return Next ;
}
return originalElement;
};
const App: React.FC = () => ;
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Pagination 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Pagination } from 'antd';
import type { PaginationProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
padding: 8px;
`,
}));
const styleFn: PaginationProps['styles'] = ({ props }) => {
if (props.size === 'small') {
return {
item: {
backgroundColor: `rgba(200, 200, 200, 0.3)`,
marginInlineEnd: 4,
},
} satisfies PaginationProps['styles'];
}
return {};
};
const App: React.FC = () => {
const paginationSharedProps: PaginationProps = {
total: 500,
classNames: { root: classNames.root },
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
```jsx
```
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| align | 对齐方式 | start \| center \| end | - | 5.19.0 |
| classNames | 自定义组件内部各语义化结构的类名。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| current | 当前页数 | number | - | |
| defaultCurrent | 默认的当前页数 | number | 1 | |
| defaultPageSize | 默认的每页条数 | number | 10 | |
| disabled | 禁用分页 | boolean | - | |
| hideOnSinglePage | 只有一页时是否隐藏分页器 | boolean | false | |
| itemRender | 用于自定义页码的结构,可用于优化 SEO | (page, type: 'page' \| 'prev' \| 'next', originalElement) => React.ReactNode | - | |
| pageSize | 每页条数 | number | - | |
| pageSizeOptions | 指定每页可以显示多少条 | number\[] | \[`10`, `20`, `50`, `100`] | |
| responsive | 当 size 未指定时,根据屏幕宽度自动调整尺寸 | boolean | - | |
| showLessItems | 是否显示较少页面内容 | boolean | false | |
| showQuickJumper | 是否可以快速跳转至某页 | boolean \| { goButton: ReactNode } | false | |
| showSizeChanger | 是否展示 `pageSize` 切换器 | boolean \| [SelectProps](/components/select-cn#api) | - | SelectProps: 5.21.0 |
| totalBoundaryShowSizeChanger | 当 `total` 大于该值时,`showSizeChanger` 默认为 true | number | 50 | |
| showTitle | 是否显示原生 tooltip 页码提示 | boolean | true | |
| showTotal | 用于显示数据总量和当前数据顺序 | function(total, range) | - | |
| simple | 当添加该属性时,显示为简单分页 | boolean \| { readOnly?: boolean } | - | |
| size | 组件尺寸 | `large` \| `medium` \| `small` | `medium` | |
| styles | 自定义组件内部各语义化结构的内联样式。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| total | 数据总数 | number | 0 | |
| onChange | 页码或 `pageSize` 改变的回调,参数是改变后的页码及每页条数 | function(page, pageSize) | - | |
| onShowSizeChange | pageSize 变化的回调 | function(current, size) | - | |
## Semantic DOM
https://ant.design/components/pagination-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Pagination)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| itemActiveBg | 页码激活态背景色 | string | #ffffff |
| itemActiveBgDisabled | 页码激活态禁用状态背景色 | string | rgba(0,0,0,0.15) |
| itemActiveColor | 页码激活态文字颜色 | string | #1677ff |
| itemActiveColorDisabled | 页码激活态禁用状态文字颜色 | string | rgba(0,0,0,0.25) |
| itemActiveColorHover | 页码激活态文字颜色悬停态 | string | #4096ff |
| itemBg | 页码选项背景色 | string | #ffffff |
| itemInputBg | 输入框背景色 | string | #ffffff |
| itemLinkBg | 页码链接背景色 | string | #ffffff |
| itemSize | 页码尺寸 | number | 32 |
| itemSizeLG | 大号页码尺寸 | number | 40 |
| itemSizeSM | 小号页码尺寸 | number | 24 |
| miniOptionsSizeChangerTop | 每页展示数量选择器 top | number | 0 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgTextActive | 控制文本在激活状态下的背景色。 | string | |
| colorBgTextHover | 控制文本在悬停状态下的背景色。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextPlaceholder | 控制占位文本的颜色。 | string | |
| controlHeightLG | 较高的组件高度 | number | |
| controlOutline | 控制输入组件的外轮廓线颜色。 | string | |
| controlOutlineWidth | 控制输入组件的外轮廓线宽度。 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeSM | 小号字体大小 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| paddingXXS | 控制元素的极小内间距。 | number | |
| screenLG | 控制大屏幕的屏幕宽度。 | number | |
| screenSM | 控制小屏幕的屏幕宽度。 | number | |
---
## popconfirm-cn
Source: https://ant.design/components/popconfirm-cn.md
---
category: Components
group: 反馈
title: Popconfirm
subtitle: 气泡确认框
description: 点击元素,弹出气泡式的确认框。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*a7tqQ6wrdeAAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*iwYsQpeFcB0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
目标元素的操作需要用户进一步的确认时,在目标元素附近弹出浮层提示,询问用户。
和 `confirm` 弹出的全屏居中模态对话框相比,交互形式更轻量。
## 代码演示 {#examples}
### 基本
最简单的用法,支持确认标题和描述。
> `description` 在 `5.1.0` 版本中支持。
```tsx
import React from 'react';
import type { PopconfirmProps } from 'antd';
import { Button, message, Popconfirm } from 'antd';
const App: React.FC = () => {
const [messageApi, holder] = message.useMessage();
const confirm: PopconfirmProps['onConfirm'] = (e) => {
console.log(e);
messageApi.success('Click on Yes');
};
const cancel: PopconfirmProps['onCancel'] = (e) => {
console.log(e);
messageApi.error('Click on No');
};
return (
<>
{holder}
Delete
>
);
};
export default App;
```
### 国际化
使用 `okText` 和 `cancelText` 自定义按钮文字。
```tsx
import React from 'react';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => (
Delete
);
export default App;
```
### 位置
位置有十二个方向。如需箭头指向目标元素中心,可以设置 `arrow: { pointAtCenter: true }`。
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex, Popconfirm } from 'antd';
const text = 'Are you sure to delete this task?';
const description = 'Delete the task';
const buttonWidth = 80;
const App: React.FC = () => (
TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
);
export default App;
```
### 贴边偏移
当 Popconfirm 贴边时,自动偏移并且调整箭头位置。当超出过多时,则一同滚出屏幕。
```tsx
import React from 'react';
import { Button, Popconfirm } from 'antd';
const style: React.CSSProperties = {
width: '300vw',
height: '300vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
const App: React.FC = () => {
React.useEffect(() => {
document.documentElement.scrollTop = document.documentElement.clientHeight;
document.documentElement.scrollLeft = document.documentElement.clientWidth;
}, []);
return (
);
};
export default App;
```
### 条件触发
可以判断是否需要弹出。
```tsx
import React, { useState } from 'react';
import { Button, message, Popconfirm, Switch } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [condition, setCondition] = useState(true);
const changeCondition = (checked: boolean) => {
setCondition(checked);
};
const confirm = () => {
setOpen(false);
message.success('Next step.');
};
const cancel = () => {
setOpen(false);
message.error('Click on cancel.');
};
const handleOpenChange = (newOpen: boolean) => {
if (!newOpen) {
setOpen(newOpen);
return;
}
// Determining condition before show the popconfirm.
console.log(condition);
if (condition) {
confirm(); // next step
} else {
setOpen(newOpen);
}
};
return (
Delete a task
Whether directly execute:
);
};
export default App;
```
### 自定义 Icon 图标
自定义提示 `icon`。
```tsx
import React from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => (
}
>
Delete
);
export default App;
```
### 异步关闭
点击确定后异步关闭气泡确认框,例如提交表单。
```tsx
import React, { useState } from 'react';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const showPopconfirm = () => {
setOpen(true);
};
const handleOk = () => {
setConfirmLoading(true);
setTimeout(() => {
setOpen(false);
setConfirmLoading(false);
}, 2000);
};
const handleCancel = () => {
console.log('Clicked cancel button');
setOpen(false);
};
return (
Open Popconfirm with async logic
);
};
export default App;
```
### 基于 Promise 的异步关闭
点击确定后异步关闭 Popconfirm,例如提交表单。
```tsx
import React from 'react';
import { Button, Popconfirm } from 'antd';
const App: React.FC = () => {
const confirm = () =>
new Promise((resolve) => {
setTimeout(() => resolve(null), 3000);
});
return (
console.log('open change')}
>
Open Popconfirm with Promise
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Popconfirm 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Button, Flex, Popconfirm } from 'antd';
import type { PopconfirmProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
container: css`
padding: 10px;
`,
}));
const styles: PopconfirmProps['styles'] = {
container: {
backgroundColor: '#eee',
boxShadow: 'inset 5px 5px 3px #fff, inset -5px -5px 3px #ddd, 0 0 3px rgba(0,0,0,0.2)',
},
title: {
color: '#262626',
},
content: {
color: '#262626',
},
};
const stylesFn: PopconfirmProps['styles'] = (info) => {
if (!info.props.arrow) {
return {
container: {
backgroundColor: 'rgba(53, 71, 125, 0.8)',
padding: 12,
borderRadius: 4,
},
title: {
color: '#fff',
},
content: {
color: '#fff',
},
} satisfies PopconfirmProps['styles'];
}
return {};
};
const App: React.FC = () => {
return (
Object Style
Function Style
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| cancelButtonProps | cancel 按钮 props | [ButtonProps](/components/button-cn#api) | - | |
| cancelText | 取消按钮文字 | string | `取消` | |
| disabled | 阻止点击 Popconfirm 子元素时弹出确认框 | boolean | false | |
| icon | 自定义弹出气泡 Icon 图标 | ReactNode | <ExclamationCircle /> | |
| okButtonProps | ok 按钮 props | [ButtonProps](/components/button-cn#api) | - | |
| okText | 确认按钮文字 | string | `确定` | |
| okType | 确认按钮类型 | string | `primary` | |
| showCancel | 是否显示取消按钮 | boolean | true | 4.18.0 |
| title | 确认框标题 | ReactNode \| () => ReactNode | - | |
| description | 确认内容的详细描述 | ReactNode \| () => ReactNode | - | 5.1.0 |
| onCancel | 点击取消的回调 | function(e) | - | |
| onConfirm | 点击确认的回调 | function(e) | - | |
| onPopupClick | 弹出气泡点击事件 | function(e) | - | 5.5.0 |
## Semantic DOM
https://ant.design/components/popconfirm-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Popconfirm)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| zIndexPopup | 确认框 z-index | number | 1060 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
## FAQ
更多问题,请参考 [Tooltip FAQ](/components/tooltip-cn#faq)。
---
## popover-cn
Source: https://ant.design/components/popover-cn.md
---
category: Components
group: 数据展示
title: Popover
subtitle: 气泡卡片
description: 点击/鼠标移入元素,弹出气泡式的卡片浮层。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*kfW5RrfF4L8AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*6b8fSKVVtXIAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
当目标元素有进一步的描述和相关操作时,可以收纳到卡片中,根据用户的操作行为进行展现。
和 `Tooltip` 的区别是,用户可以对浮层上的元素进行操作,因此它可以承载更复杂的内容,比如链接或按钮等。
## 代码演示 {#examples}
### 基本
最简单的用法,浮层的大小由内容区域决定。
```tsx
import React from 'react';
import { Button, Popover } from 'antd';
const content = (
);
const App: React.FC = () => (
Hover me
);
export default App;
```
### 三种触发方式
鼠标移入、聚集、点击。
```tsx
import React from 'react';
import { Button, Popover, Space } from 'antd';
const content = (
);
const App: React.FC = () => (
Hover me
Focus me
Click me
);
export default App;
```
### 位置
位置有十二个方向。
```tsx
import React from 'react';
import { Button, ConfigProvider, Flex, Popover } from 'antd';
const text = Title ;
const content = (
);
const buttonWidth = 80;
const App: React.FC = () => (
TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
);
export default App;
```
### 箭头展示
通过 `arrow` 属性隐藏箭头。
```tsx
import React, { useMemo, useState } from 'react';
import { Button, ConfigProvider, Flex, Popover, Segmented } from 'antd';
import type { PopoverProps } from 'antd';
const text = Title ;
const buttonWidth = 80;
const content = (
);
const App: React.FC = () => {
const [arrow, setArrow] = useState<'Show' | 'Hide' | 'Center'>('Show');
const mergedArrow = useMemo(() => {
if (arrow === 'Hide') {
return false;
}
if (arrow === 'Show') {
return true;
}
return {
pointAtCenter: true,
};
}, [arrow]);
return (
TL
Top
TR
LT
Left
LB
RT
Right
RB
BL
Bottom
BR
);
};
export default App;
```
### 贴边偏移
当 Popover 贴边时,自动偏移并且调整箭头位置。当超出过多时,则一同滚出屏幕。
```tsx
import React from 'react';
import { Button, Popover } from 'antd';
const style: React.CSSProperties = {
width: '300vw',
height: '300vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
const App: React.FC = () => {
React.useEffect(() => {
document.documentElement.scrollTop = document.documentElement.clientHeight;
document.documentElement.scrollLeft = document.documentElement.clientWidth;
}, []);
return (
);
};
export default App;
```
### 从浮层内关闭
使用 `open` 属性控制浮层显示。
```tsx
import React, { useState } from 'react';
import { Button, Popover } from 'antd';
const App: React.FC = () => {
const [open, setOpen] = useState(false);
const hide = () => {
setOpen(false);
};
const handleOpenChange = (newOpen: boolean) => {
setOpen(newOpen);
};
return (
Close}
title="Title"
trigger="click"
open={open}
onOpenChange={handleOpenChange}
>
Click me
);
};
export default App;
```
### 悬停点击弹出窗口
以下示例显示如何创建可悬停和单击的弹出窗口。
```tsx
import React, { useState } from 'react';
import { Button, Popover } from 'antd';
const hoverContent = This is hover content.
;
const clickContent = This is click content.
;
const App: React.FC = () => {
const [clicked, setClicked] = useState(false);
const [hovered, setHovered] = useState(false);
const hide = () => {
setClicked(false);
setHovered(false);
};
const handleHoverChange = (open: boolean) => {
setHovered(open);
setClicked(false);
};
const handleClickChange = (open: boolean) => {
setHovered(false);
setClicked(open);
};
return (
{clickContent}
Close
}
title="Click title"
trigger="click"
open={clicked}
onOpenChange={handleClickChange}
>
Hover and click
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Popover 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Button, Flex, Popover } from 'antd';
import type { PopoverProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
container: css`
padding: 10px;
`,
}));
const styles: PopoverProps['styles'] = {
container: {
background: '#eee',
boxShadow: 'inset 5px 5px 3px #fff, inset -5px -5px 3px #ddd, 0 0 3px rgba(0,0,0,0.2)',
},
content: {
color: '#262626',
},
};
const stylesFn: PopoverProps['styles'] = (info) => {
if (!info.props.arrow) {
return {
container: {
backgroundColor: 'rgba(53, 71, 125, 0.8)',
padding: 12,
borderRadius: 4,
},
content: {
color: '#fff',
},
} satisfies PopoverProps['styles'];
}
return {};
};
const App: React.FC = () => {
return (
Object Style
Function Style
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| content | 卡片内容 | ReactNode \| () => ReactNode | - | |
| title | 卡片标题 | ReactNode \| () => ReactNode | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
## 注意
请确保 `Popover` 的子元素能接受 `onMouseEnter`、`onMouseLeave`、`onFocus`、`onClick` 事件。
## Semantic DOM
https://ant.design/components/popover-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Popover)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| titleMinWidth | 气泡卡片标题最小宽度 | string \| number | 177 |
| zIndexPopup | 气泡卡片 z-index | number | 1030 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| boxShadowSecondary | 控制元素二级阴影样式。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontWeightStrong | 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 | number | |
| lineHeight | 文本行高 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| motionEaseOutCirc | 预设动效曲率 | string | |
| sizePopupArrow | 组件箭头的尺寸 | number | |
## FAQ
更多问题,请参考 [Tooltip FAQ](/components/tooltip-cn#faq)。
---
## progress-cn
Source: https://ant.design/components/progress-cn.md
---
category: Components
group: 反馈
title: Progress
subtitle: 进度条
description: 展示操作的当前进度。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*gK_4S6fDRfgAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*HJH8Tb1lcYAAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。
- 当一个操作会打断当前界面,或者需要在后台运行,且耗时可能超过 2 秒时;
- 当需要显示一个操作完成的百分比时。
## 代码演示 {#examples}
### 进度条
标准的进度条。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 进度圈
圈形的进度。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 小型进度条
适合放在较狭窄的区域内。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 响应式进度圈
响应式的圈形进度,当 `width` 小于等于 20 的时候,进度信息将不会显示在进度圈里面,而是以 Tooltip 的形式显示。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
`进行中,已完成${number}%`}
/>
代码发布
);
export default App;
```
### 小型进度圈
小一号的圈形进度。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 动态展示
会动的进度条才是好进度条。
```tsx
import React, { useState } from 'react';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Flex, Progress, Space } from 'antd';
const App: React.FC = () => {
const [percent, setPercent] = useState(0);
const increase = () => {
setPercent((prevPercent) => {
const newPercent = prevPercent + 10;
if (newPercent > 100) {
return 100;
}
return newPercent;
});
};
const decline = () => {
setPercent((prevPercent) => {
const newPercent = prevPercent - 10;
if (newPercent < 0) {
return 0;
}
return newPercent;
});
};
return (
} />
} />
);
};
export default App;
```
### 自定义文字格式
`format` 属性指定格式。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
`${percent} Days`} />
'Done'} />
);
export default App;
```
### 仪表盘
通过设置 `type=dashboard`,可以很方便地实现仪表盘样式的进度条。
```tsx
import React, { useState } from 'react';
import { Flex, Progress, Segmented } from 'antd';
import type { GapPlacement } from '../progress';
const App: React.FC = () => {
const [gapPlacement, setGapPlacement] = useState('bottom');
const [gapDegree, setGapDegree] = useState(50);
return (
gapDegree:
{
setGapDegree(value);
}}
/>
gapPlacement:
{
setGapPlacement(value);
}}
/>
);
};
export default App;
```
### 分段进度条
分段展示进度,可以用于细化进度语义。
```tsx
import React from 'react';
import { Flex, Progress, Tooltip } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 边缘形状
通过设定 `strokeLinecap="butt"` 可以将进度条边缘的形状从闭合的圆形的圆弧调整为断口,详见 [stroke-linecap](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap)。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义进度条渐变色
渐变色封装,`circle` 与 `dashboard` 设置渐变时 `strokeLinecap` 会被忽略。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
import type { ProgressProps } from 'antd';
const twoColors: ProgressProps['strokeColor'] = {
'0%': '#108ee9',
'100%': '#87d068',
};
const conicColors: ProgressProps['strokeColor'] = {
'0%': '#87d068',
'50%': '#ffe58f',
'100%': '#ffccc7',
};
const App: React.FC = () => (
);
export default App;
```
### 步骤进度条
带步骤的进度条。
```tsx
import React from 'react';
import { green, red } from '@ant-design/colors';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 步骤进度圈
步骤进度圈,支持颜色分段展示,默认间隔为 2px。
```tsx
import React from 'react';
import { Flex, Progress, Slider, Typography } from 'antd';
const App: React.FC = () => {
const [stepsCount, setStepsCount] = React.useState(5);
const [stepsGap, setStepsGap] = React.useState(7);
return (
<>
Custom count:
Custom gap:
>
);
};
export default App;
```
### 尺寸
进度条尺寸。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 改变进度数值位置
改变进度数值位置,可使用 `percentPosition` 调整,使进度条数值在进度条内部、外部或底部。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象或者函数可以自定义 Progress 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Progress } from 'antd';
import type { ProgressProps } from 'antd';
const classNames: ProgressProps['classNames'] = {
root: 'demo-progress-root',
rail: 'demo-progress-rail',
track: 'demo-progress-track',
};
const stylesFn: ProgressProps['styles'] = (info) => {
const percent = info?.props?.percent ?? 0;
const hue = 200 - (200 * percent) / 100;
return {
track: {
backgroundImage: `
linear-gradient(
to right,
hsla(${hue}, 85%, 65%, 1),
hsla(${hue + 30}, 90%, 55%, 0.95)
)`,
borderRadius: 8,
transition: 'all 0.3s ease',
},
rail: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
borderRadius: 8,
},
} satisfies ProgressProps['styles'];
};
const App: React.FC = () => (
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
各类型共用的属性。
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| format | 内容的模板函数 | function(percent, successPercent) | (percent) => percent + `%` | - |
| percent | 百分比 | number | 0 | - |
| railColor | 未完成的分段的颜色 | string | - | - |
| showInfo | 是否显示进度数值或状态图标 | boolean | true | - |
| status | 状态,可选:`success` `exception` `normal` `active`(仅限 line) | string | - | - |
| strokeColor | 进度条的色彩 | string | - | - |
| strokeLinecap | 进度条的样式 | `round` \| `butt` \| `square`,区别详见 [stroke-linecap](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) | `round` | - |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| success | 成功进度条相关配置 | { percent: number, strokeColor: string } | - | - |
| ~~trailColor~~ | 未完成的分段的颜色。已废弃,请使用 `railColor` | string | - | - |
| type | 类型,可选 `line` `circle` `dashboard` | string | `line` | - |
| size | 进度条的尺寸 | number \| \[number \| string, number] \| { width: number, height: number } \| "small" \| "default" | "default" | 5.3.0, Object: 5.18.0 |
### `type="line"`
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| steps | 进度条总共步数 | number | - | - |
| rounding | 用于四舍五入数值的函数 | (step: number) => number | Math.round | 5.24.0 |
| strokeColor | 进度条的色彩,传入 object 时为渐变。当有 `steps` 时支持传入一个数组。 | string \| string[] \| { from: string; to: string; direction: string } | - | 4.21.0: `string[]` |
| percentPosition | 进度数值位置,传入对象,`align` 表示数值的水平位置,`type` 表示数值在进度条内部还是外部 | { align: string; type: string } | { align: \"end\", type: \"outer\" } | 5.18.0 |
### `type="circle"`
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| steps | 进度条总共步数,传入 object 时,count 指步数,gap 指间隔大小。传 number 类型时,gap 默认为 2。 | number \| { count: number, gap: number } | - | 5.16.0 |
| strokeColor | 圆形进度条线的色彩,传入 object 时为渐变 | string \| { number%: string } | - | - |
| strokeWidth | 圆形进度条线的宽度,单位是进度条画布宽度的百分比 | number | 6 | - |
### `type="dashboard"`
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| steps | 进度条总共步数,传入 object 时,count 指步数,gap 指间隔大小。传 number 类型时,gap 默认为 2。 | number \| { count: number, gap: number } | - | 5.16.0 |
| gapDegree | 仪表盘进度条缺口角度,可取值 0 ~ 295 | number | 75 | - |
| gapPlacement | 仪表盘进度条缺口位置 | `top` \| `bottom` \| `start` \| `end` | `bottom` | - |
| ~~gapPosition~~ | 仪表盘进度条缺口位置,请使用 `gapPlacement` 替换 | `top` \| `bottom` \| `left` \| `right` | `bottom` | - |
| strokeWidth | 仪表盘进度条线的宽度,单位是进度条画布宽度的百分比 | number | 6 | - |
## Semantic DOM
https://ant.design/components/progress-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Progress)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| circleIconFontSize | 圆形进度条图标大小 | string | 1.1666666666666667em |
| circleTextColor | 圆形进度条文字颜色 | string | rgba(0,0,0,0.88) |
| circleTextFontSize | 圆形进度条文本大小 | string | 1em |
| defaultColor | 进度条默认颜色 | string | #1677ff |
| lineBorderRadius | 条状进度条圆角 | number | 100 |
| remainingColor | 进度条剩余部分颜色 | string | rgba(0,0,0,0.06) |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorSuccess | 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorWhite | 不随主题变化的纯白色 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| motionEaseOutQuint | 预设动效曲率 | string | |
| paddingXXS | 控制元素的极小内间距。 | number | |
---
## qr-code-cn
Source: https://ant.design/components/qr-code-cn.md
---
category: Components
title: QRCode
subtitle: 二维码
description: 能够将文本转换生成二维码的组件,支持自定义配色和 Logo 配置。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*cJopQrf0ncwAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*M4PBTZ_n9OgAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
group:
title: 数据展示
order: 5
---
## 何时使用 {#when-to-use}
当需要将文本转换成为二维码时使用。
## 代码演示 {#examples}
### 基本使用
基本用法。
```tsx
import React from 'react';
import { Input, QRCode, Space } from 'antd';
const App: React.FC = () => {
const [text, setText] = React.useState('https://ant.design/');
return (
setText(e.target.value)}
/>
);
};
export default App;
```
### 带 Icon 的例子
带 Icon 的二维码。
```tsx
import React from 'react';
import { QRCode } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 不同的状态
可以通过 `status` 的值控制二维码的状态,提供了 `active`、`expired`、`loading`、`scanned` 四个值。
```tsx
import React from 'react';
import { Flex, QRCode } from 'antd';
const value = 'https://ant.design';
const App: React.FC = () => (
console.log('refresh')} />
);
export default App;
```
### 自定义状态渲染器
可以通过 `statusRender` 的值控制二维码不同状态的渲染逻辑。
```tsx
import React from 'react';
import { CheckCircleFilled, CloseCircleFilled, ReloadOutlined } from '@ant-design/icons';
import type { QRCodeProps } from 'antd';
import { Button, Flex, QRCode, Space, Spin } from 'antd';
const value = 'https://ant.design';
const customStatusRender: QRCodeProps['statusRender'] = (info) => {
switch (info.status) {
case 'expired':
return (
{info.locale?.expired}
{info.locale?.refresh}
);
case 'loading':
return (
Loading...
);
case 'scanned':
return (
{info.locale?.scanned}
);
default:
return null;
}
};
const App: React.FC = () => (
console.log('refresh')}
statusRender={customStatusRender}
/>
);
export default App;
```
### 自定义渲染类型
通过设置 `type` 自定义渲染结果,提供 `canvas` 和 `svg` 两个选项。
```tsx
import React from 'react';
import { QRCode, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义尺寸
自定义尺寸
```tsx
import React, { useState } from 'react';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, QRCode, Space } from 'antd';
const MIN_SIZE = 48;
const MAX_SIZE = 300;
const App: React.FC = () => {
const [size, setSize] = useState(160);
const increase = () => {
setSize((prevSize) => {
const newSize = prevSize + 10;
if (newSize >= MAX_SIZE) {
return MAX_SIZE;
}
return newSize;
});
};
const decline = () => {
setSize((prevSize) => {
const newSize = prevSize - 10;
if (newSize <= MIN_SIZE) {
return MIN_SIZE;
}
return newSize;
});
};
return (
<>
}>
Smaller
= MAX_SIZE} icon={ }>
Larger
>
);
};
export default App;
```
### 自定义颜色
通过设置 `color` 自定义二维码颜色,通过设置 `bgColor` 自定义背景颜色。
```tsx
import React from 'react';
import { QRCode, Space, theme } from 'antd';
const { useToken } = theme;
const App: React.FC = () => {
const { token } = useToken();
return (
);
};
export default App;
```
### 下载二维码
下载二维码的简单实现。
```tsx
import React from 'react';
import { Button, QRCode, Segmented, Space } from 'antd';
import type { QRCodeProps } from 'antd';
function doDownload(url: string, fileName: string) {
const a = document.createElement('a');
a.download = fileName;
a.href = url;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
const downloadCanvasQRCode = () => {
const canvas = document.getElementById('myqrcode')?.querySelector('canvas');
if (canvas) {
const url = canvas.toDataURL();
doDownload(url, 'QRCode.png');
}
};
const downloadSvgQRCode = () => {
const svg = document.getElementById('myqrcode')?.querySelector('svg');
const svgData = new XMLSerializer().serializeToString(svg!);
const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
doDownload(url, 'QRCode.svg');
};
const App: React.FC = () => {
const [renderType, setRenderType] = React.useState('canvas');
return (
Download
);
};
export default App;
```
### 纠错比例
通过设置 errorLevel 调整不同的容错等级。
```tsx
import React, { useState } from 'react';
import type { QRCodeProps } from 'antd';
import { QRCode, Segmented } from 'antd';
const App: React.FC = () => {
const [level, setLevel] = useState('L');
return (
<>
>
);
};
export default App;
```
### 高级用法
带气泡卡片的例子。
```tsx
import React from 'react';
import { Button, Popover, QRCode } from 'antd';
const App: React.FC = () => (
}>
Hover me
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 QRCode 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, QRCode } from 'antd';
import type { QRCodeProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 1px solid #ccc;
border-radius: 8px;
padding: 16px;
`,
}));
const stylesObject: QRCodeProps['styles'] = {
root: {
border: '2px solid #1890ff',
borderRadius: 8,
padding: 16,
backgroundColor: 'rgb(24, 144, 255, 0.1)',
},
};
const stylesFunction: QRCodeProps['styles'] = (info) => {
if (info.props.type === 'canvas') {
return {
root: {
border: '2px solid #ff4d4f',
borderRadius: 8,
padding: 16,
backgroundColor: 'rgba(255, 77, 79, 0.1)',
},
} satisfies QRCodeProps['styles'];
}
};
const App: React.FC = () => {
const sharedProps: QRCodeProps = {
value: 'https://ant.design/',
size: 160,
classNames,
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> 自 `antd@5.1.0` 版本开始提供该组件。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| :-- | :-- | :-- | :-- | :-- |
| value | 扫描后的文本 | `string \| string[]` | - | `string[]`: 5.28.0 |
| type | 渲染类型 | `canvas \| svg ` | `canvas` | 5.6.0 |
| icon | 二维码中图片的地址(目前只支持图片地址) | string | - |
| size | 二维码大小 | number | 160 |
| iconSize | 二维码中图片的大小 | number \| { width: number; height: number } | 40 | 5.19.0 |
| color | 二维码颜色 | string | `#000` |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| bgColor | 二维码背景颜色 | string | `transparent` | 5.5.0 |
| marginSize | 留白(安静区)大小(单位为模块数),`0` 表示无留白 | number | `0` | 6.2.0 |
| bordered | 是否有边框 | boolean | `true` |
| errorLevel | 二维码纠错等级 | `'L' \| 'M' \| 'Q' \| 'H' ` | `M` |
| boostLevel | 如果启用,自动提升纠错等级,结果的纠错级别可能会高于指定的纠错级别 | `boolean` | true | 5.28.0 |
| status | 二维码状态 | `active \| expired \| loading \| scanned` | `active` | scanned: 5.13.0 |
| statusRender | 自定义状态渲染器 | (info: [StatusRenderInfo](/components/qr-code-cn#statusrenderinfo)) => React.ReactNode | - | 5.20.0 |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| type | 渲染类型 | `canvas \| svg` | `canvas` | 5.6.0 |
| value | 扫描后的文本 | string | - | |
### StatusRenderInfo
```typescript
type StatusRenderInfo = {
status: QRStatus;
locale: Locale['QRCode'];
onRefresh?: () => void;
};
```
## Semantic DOM
https://ant.design/components/qr-code-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorWhite | 不随主题变化的纯白色 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| paddingSM | 控制元素的小内间距。 | number | |
## FAQ
### 关于二维码纠错等级 {#faq-error-correction-level}
纠错等级也叫纠错率,就是指二维码可以被遮挡后还能正常扫描,而这个能被遮挡的最大面积就是纠错率。
通常情况下二维码分为 4 个纠错级别:`L级` 可纠正约 `7%` 错误、`M级` 可纠正约 `15%` 错误、`Q级` 可纠正约 `25%` 错误、`H级` 可纠正约`30%` 错误。并不是所有位置都可以缺损,像最明显的三个角上的方框,直接影响初始定位。中间零散的部分是内容编码,可以容忍缺损。当二维码的内容编码携带信息比较少的时候,也就是链接比较短的时候,设置不同的纠错等级,生成的图片不会发生变化。
> 有关更多信息,可参阅相关资料:[https://www.qrcode.com/zh/about/error_correction](https://www.qrcode.com/zh/about/error_correction.html)
### ⚠️⚠️⚠️ 二维码无法扫描? {#faq-cannot-scan}
若二维码无法扫码识别,可能是因为链接地址过长导致像素过于密集,可以通过 size 配置二维码更大,或者通过短链接服务等方式将链接变短。
---
## radio-cn
Source: https://ant.design/components/radio-cn.md
---
category: Components
group: 数据录入
title: Radio
subtitle: 单选框
description: 用于在多个备选项中选中单个状态。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*mrPVRope68wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*xPfTSphsiA0AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 用于在多个备选项中选中单个状态。
- 和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。
```tsx
// 使用 Radio.Group 组件时,推荐的写法 ✅
return (
);
// 不推荐的写法 🙅🏻♀️
return (
A
B
C
);
```
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Radio } from 'antd';
const App: React.FC = () => Radio ;
export default App;
```
### 不可用
Radio 不可用。
```tsx
import React, { useState } from 'react';
import { Button, Radio } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(true);
const toggleDisabled = () => {
setDisabled(!disabled);
};
return (
<>
Disabled
Disabled
Toggle disabled
>
);
};
export default App;
```
### 单选组合
一组互斥的 Radio 配合使用。
```tsx
import React, { useState } from 'react';
import {
BarChartOutlined,
DotChartOutlined,
LineChartOutlined,
PieChartOutlined,
} from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Flex, Radio } from 'antd';
const App: React.FC = () => {
const [value, setValue] = useState(1);
const onChange = (e: RadioChangeEvent) => {
setValue(e.target.value);
};
return (
LineChart
),
},
{
value: 2,
className: 'option-2',
label: (
DotChart
),
},
{
value: 3,
className: 'option-3',
label: (
BarChart
),
},
{
value: 4,
className: 'option-4',
label: (
PieChart
),
},
]}
/>
);
};
export default App;
```
### Radio.Group 垂直
垂直的 Radio.Group,配合更多输入框选项。
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Input, Radio } from 'antd';
const labelStyle: React.CSSProperties = {
height: 32,
lineHeight: '32px',
};
const App: React.FC = () => {
const [value, setValue] = useState(1);
const onChange = (e: RadioChangeEvent) => {
setValue(e.target.value);
};
return (
More...
{value === 4 && (
)}
>
),
},
]}
/>
);
};
export default App;
```
### Block 单选组合
`block` 属性将使 Radio.Group 撑满父容器。
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
const options: CheckboxGroupProps['options'] = [
{ label: 'Apple', value: 'Apple' },
{ label: 'Pear', value: 'Pear' },
{ label: 'Orange', value: 'Orange' },
];
const App: React.FC = () => (
);
export default App;
```
### Radio.Group 组合 - 配置方式
通过配置 `options` 参数来渲染单选框。也可通过 `optionType` 参数来设置 Radio 类型。
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent } from 'antd';
import { Radio } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
const plainOptions: CheckboxGroupProps['options'] = ['Apple', 'Pear', 'Orange'];
const options: CheckboxGroupProps['options'] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', title: 'Orange', className: 'label-3' },
];
const optionsWithDisabled: CheckboxGroupProps['options'] = [
{ label: 'Apple', value: 'Apple', className: 'label-1' },
{ label: 'Pear', value: 'Pear', className: 'label-2' },
{ label: 'Orange', value: 'Orange', className: 'label-3', disabled: true },
];
const App: React.FC = () => {
const [value1, setValue1] = useState('Apple');
const [value2, setValue2] = useState('Apple');
const [value3, setValue3] = useState('Apple');
const [value4, setValue4] = useState('Apple');
const onChange1 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio1 checked', value);
setValue1(value);
};
const onChange2 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio2 checked', value);
setValue2(value);
};
const onChange3 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio3 checked', value);
setValue3(value);
};
const onChange4 = ({ target: { value } }: RadioChangeEvent) => {
console.log('radio4 checked', value);
setValue4(value);
};
return (
<>
>
);
};
export default App;
```
### 按钮样式
按钮样式的单选组合。
```tsx
import React from 'react';
import type { RadioChangeEvent } from 'antd';
import { Flex, Radio } from 'antd';
const onChange = (e: RadioChangeEvent) => {
console.log(`radio checked:${e.target.value}`);
};
const App: React.FC = () => (
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
);
export default App;
```
### 单选组合 - 配合 name 使用
可以为 Radio.Group 配置 `name` 参数,为组合内的 input 元素赋予相同的 `name` 属性,使浏览器把 Radio.Group 下的 Radio 真正看作是一组(例如可以通过方向键始终**在同一组内**更改选项)。
```tsx
import React from 'react';
import { Radio } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 大小
大中小三种组合,可以和表单输入框进行对应配合。
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
const App: React.FC = () => (
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
);
export default App;
```
### 填底的按钮样式
实色填底的单选按钮样式。
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
const App: React.FC = () => (
Hangzhou
Shanghai
Beijing
Chengdu
Hangzhou
Shanghai
Beijing
Chengdu
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义单选框的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Radio } from 'antd';
import type { RadioProps } 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: RadioProps['styles'] = {
icon: {
borderRadius: 6,
},
label: {
color: 'blue',
},
};
const App: React.FC = () => {
const [value, setValue] = React.useState<'styles' | 'classNames'>('styles');
const { styles: classNamesStyles } = useStyles();
// Function classNames - dynamically adjust based on checked state
const classNamesFn: RadioProps['classNames'] = (info) => {
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 (
setValue('styles')}
>
Object styles
setValue('classNames')}
>
Function classNames
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Radio/Radio.Button
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| checked | 指定当前是否选中 | boolean | false | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 |
| defaultChecked | 初始是否选中 | boolean | false | |
| disabled | 禁用 Radio | boolean | false | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 |
| value | 根据 value 进行比较,判断是否选中 | any | - | |
### Radio.Group
单选框组合,用于包裹一组 `Radio`。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| block | 将 RadioGroup 宽度调整为其父宽度的选项 | boolean | false | 5.21.0 |
| buttonStyle | RadioButton 的风格样式,目前有描边和填色两种风格 | `outline` \| `solid` | `outline` | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | 6.0.0 |
| defaultValue | 默认选中的值 | any | - | |
| disabled | 禁选所有子单选器 | boolean | false | |
| name | RadioGroup 下所有 `input[type="radio"]` 的 `name` 属性。若未设置,则将回退到随机生成的名称 | string | - | |
| options | 以配置形式设置子元素 | string\[] \| number\[] \| Array<[CheckboxOptionType](#checkboxoptiontype)> | - | |
| optionType | 用于设置 Radio `options` 类型 | `default` \| `button` | `default` | 4.4.0 |
| orientation | 排列方向 | `horizontal` \| `vertical` | `horizontal` | |
| size | 大小,只对按钮样式生效 | `large` \| `middle` \| `small` | - | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | 6.0.0 |
| value | 用于设置当前选中的值 | any | - | |
| vertical | 值为 true,Radio Group 为垂直方向。与 `orientation` 同时存在,以 `orientation` 优先 | boolean | false | |
| onChange | 选项变化时的回调函数 | function(e:Event) | - | |
### CheckboxOptionType
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| label | 用于作为 Radio 选项展示的文本 | `string` | - | 4.4.0 |
| value | 关联 Radio 选项的值 | `string` \| `number` \| `boolean` | - | 4.4.0 |
| style | 应用到 Radio 选项的 style | `React.CSSProperties` | - | 4.4.0 |
| className | Radio 选项的类名 | `string` | - | 5.25.0 |
| disabled | 指定 Radio 选项是否要禁用 | `boolean` | `false` | 4.4.0 |
| title | 添加 Title 属性值 | `string` | - | 4.4.0 |
| id | 添加 Radio Id 属性值 | `string` | - | 4.4.0 |
| onChange | 当 Radio Group 的值发送改变时触发 | `(e: CheckboxChangeEvent) => void;` | - | 4.4.0 |
| required | 指定 Radio 选项是否必填 | `boolean` | `false` | 4.4.0 |
## 方法
### Radio
| 名称 | 描述 |
| ------- | -------- |
| blur() | 移除焦点 |
| focus() | 获取焦点 |
## Semantic DOM
https://ant.design/components/radio-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Radio)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| buttonBg | 单选框按钮背景色 | string | #ffffff |
| buttonCheckedBg | 单选框按钮选中背景色 | string | #ffffff |
| buttonCheckedBgDisabled | 单选框按钮选中并禁用时的背景色 | string | rgba(0,0,0,0.15) |
| buttonCheckedColorDisabled | 单选框按钮选中并禁用时的文本颜色 | string | rgba(0,0,0,0.25) |
| buttonColor | 单选框按钮文本颜色 | string | rgba(0,0,0,0.88) |
| buttonPaddingInline | 单选框按钮横向内间距 | number | 15 |
| buttonSolidCheckedActiveBg | 单选框实色按钮选中时的激活态背景色 | string | #0958d9 |
| buttonSolidCheckedBg | 单选框实色按钮选中时的背景色 | string | #1677ff |
| buttonSolidCheckedColor | 单选框实色按钮选中时的文本颜色 | string | #fff |
| buttonSolidCheckedHoverBg | 单选框实色按钮选中时的悬浮态背景色 | string | #4096ff |
| dotColorDisabled | 单选框圆点禁用颜色 | string | rgba(0,0,0,0.25) |
| dotSize | 单选框圆点大小 | number | 8 |
| radioSize | 单选框大小 | number | 16 |
| wrapperMarginInlineEnd | 单选框右间距 | number | 8 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryActive | 主色梯度下的深色激活态。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | 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 | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOutCirc | 预设动效曲率 | string | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## rate-cn
Source: https://ant.design/components/rate-cn.md
---
category: Components
group: 数据录入
title: Rate
subtitle: 评分
description: 用于对事物进行评分操作。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*oyOcTrB12_YAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*M7_ER7GJr6wAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 对评价进行展示。
- 对事物进行快速的评级操作。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Rate } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 尺寸
三种尺寸。
```tsx
import React from 'react';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 半星
支持选中半星。
```tsx
import React from 'react';
import { Rate } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 文案展现
给评分组件加上文案展示。
```tsx
import React, { useState } from 'react';
import { Flex, Rate } from 'antd';
import type { RateProps } from 'antd';
const desc: RateProps['tooltips'] = [
'terrible',
{ placement: 'top', title: 'bad', trigger: 'hover' },
'normal',
'good',
'wonderful',
];
function getDescTitle(value: number, desc: RateProps['tooltips']) {
const item = desc?.[value - 1];
return typeof item === 'object' ? item.title : item;
}
const App: React.FC = () => {
const [value, setValue] = useState(3);
return (
{value ? {getDescTitle(value, desc) as React.ReactNode} : null}
);
};
export default App;
```
### 只读
只读,无法进行鼠标交互。
```tsx
import React from 'react';
import { Rate } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 清除
支持允许或者禁用清除。
```tsx
import React from 'react';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
allowClear: true
allowClear: false
);
export default App;
```
### 其他字符
可以将星星替换为其他字符,比如字母,数字,字体图标甚至中文。
```tsx
import React from 'react';
import { HeartOutlined } from '@ant-design/icons';
import { Flex, Rate } from 'antd';
const App: React.FC = () => (
} allowHalf />
);
export default App;
```
### 自定义字符
可以使用 `(RateProps) => ReactNode` 的方式自定义每一个字符。
```tsx
import React from 'react';
import { FrownOutlined, MehOutlined, SmileOutlined } from '@ant-design/icons';
import { Flex, Rate } from 'antd';
const customIcons: Record = {
1: ,
2: ,
3: ,
4: ,
5: ,
};
const App: React.FC = () => (
index + 1} />
customIcons[index + 1]} />
);
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| allowClear | 是否允许再次点击后清除 | boolean | true | |
| allowHalf | 是否允许半选 | boolean | false | |
| character | 自定义字符 | ReactNode \| (RateProps) => ReactNode | <StarFilled /> | function(): 4.4.0 |
| className | 自定义样式类名 | string | - | |
| count | star 总数 | number | 5 | |
| defaultValue | 默认值 | number | 0 | |
| disabled | 只读,无法进行交互 | boolean | false | |
| keyboard | 支持使用键盘操作 | boolean | true | 5.18.0 |
| size | 星星尺寸 | 'small' \| 'middle' \| 'large' | 'middle' | |
| style | 自定义样式对象 | CSSProperties | - | |
| tooltips | 自定义每项的提示信息 | [TooltipProps](/components/tooltip-cn#api)[] \| string\[] | - | |
| value | 当前数,受控值 | number | - | |
| onBlur | 失去焦点时的回调 | function() | - | |
| onChange | 选择时的回调 | function(value: number) | - | |
| onFocus | 获取焦点时的回调 | function() | - | |
| onHoverChange | 鼠标经过时数值变化的回调 | function(value: number) | - | |
| onKeyDown | 按键回调 | function(event) | - | |
## 方法
| 名称 | 描述 |
| ------- | -------- |
| blur() | 移除焦点 |
| focus() | 获取焦点 |
## 主题变量(Design Token){#design-token}
## 组件 Token (Rate)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| starBg | 星星背景色 | string | rgba(0,0,0,0.06) |
| starColor | 星星颜色 | string | #fadb14 |
| starHoverScale | 星星悬浮时的缩放 | readonly string[] \| Transform \| readonly Transform[] \| { _multi_value_?: boolean; _skip_check_?: boolean; value: readonly string[] \| Transform \| (readonly string[] \| Transform \| undefined)[] \| undefined } \| undefined | scale(1.1) |
| starSize | 星星尺寸 | number | 20 |
| starSizeLG | 大星星尺寸 | number | 25 |
| starSizeSM | 小星星尺寸 | number | 15 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
---
## result-cn
Source: https://ant.design/components/result-cn.md
---
group: 反馈
category: Components
title: Result
subtitle: 结果
description: 用于反馈一系列操作任务的处理结果。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-e2IRroDJyEAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-0kxQrbHx2kAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
当有重要操作需告知用户处理结果,且反馈内容较为复杂时使用。
## 代码演示 {#examples}
### Success
成功的结果。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Go Console
,
Buy Again ,
]}
/>
);
export default App;
```
### Info
展示处理结果。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Go Console
}
/>
);
export default App;
```
### Warning
警告类型的结果。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Go Console
}
/>
);
export default App;
```
### 403
你没有此页面的访问权限。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Back Home}
/>
);
export default App;
```
### 404
此页面未找到。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Back Home}
/>
);
export default App;
```
### 500
服务器发生了错误。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
const App: React.FC = () => (
Back Home}
/>
);
export default App;
```
### Error
复杂的错误反馈。
```tsx
import React from 'react';
import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Result, Typography } from 'antd';
const { Paragraph, Text } = Typography;
const App: React.FC = () => (
Go Console
,
Buy Again ,
]}
>
);
export default App;
```
### 自定义 icon
自定义 icon。
```tsx
import React from 'react';
import { SmileOutlined } from '@ant-design/icons';
import { Button, Result } from 'antd';
const App: React.FC = () => (
}
title="Great, we have done all the operations!"
extra={Next }
/>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Result 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Button, Result } from 'antd';
import type { ResultProps } from 'antd';
const classNamesObject: ResultProps['classNames'] = {
root: 'demo-result-root',
title: 'demo-result-title',
subTitle: 'demo-result-subtitle',
icon: 'demo-result-icon',
extra: 'demo-result-extra',
body: 'demo-result-body',
};
const classNamesFn: ResultProps['classNames'] = (info) => {
if (info.props.status === 'success') {
return {
root: 'demo-result-root--success',
} satisfies ResultProps['classNames'];
}
return {
root: 'demo-result-root--default',
} satisfies ResultProps['classNames'];
};
const stylesObject: ResultProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed', padding: 16 },
title: { fontStyle: 'italic', color: '#1890ff' },
subTitle: { fontWeight: 'bold' },
icon: { opacity: 0.8 },
extra: { backgroundColor: '#f0f0f0', padding: 8 },
body: { backgroundColor: '#fafafa', padding: 12 },
};
const stylesFn: ResultProps['styles'] = (info) => {
if (info.props.status === 'error') {
return {
root: { backgroundColor: '#fff2f0', borderColor: '#ff4d4f' },
title: { color: '#ff4d4f' },
} satisfies ResultProps['styles'];
} else {
return {
root: { backgroundColor: '#f6ffed', borderColor: '#52c41a' },
title: { color: '#52c41a' },
} satisfies ResultProps['styles'];
}
};
const App: React.FC = () => {
return (
<>
Action}
>
Content area
Action}
/>
>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 自定义组件内部各语义化结构的类名。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| extra | 操作区 | ReactNode | - | |
| icon | 自定义 icon | ReactNode | - | |
| status | 结果的状态,决定图标和颜色 | `success` \| `error` \| `info` \| `warning` \| `404` \| `403` \| `500` | `info` |
| styles | 自定义组件内部各语义化结构的内联样式。支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| subTitle | subTitle 文字 | ReactNode | - | |
| title | title 文字 | ReactNode | - | |
## Semantic DOM
https://ant.design/components/result-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Result)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| extraMargin | 额外区域外间距 | Margin \| undefined | 24px 0 0 0 |
| iconFontSize | 图标大小 | number | 72 |
| subtitleFontSize | 副标题字体大小 | number | 14 |
| titleFontSize | 标题字体大小 | number | 24 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorFillAlter | 控制元素替代背景色。 | string | |
| colorInfo | 用于表示操作信息的 Token 序列,如 Alert 、Tag、 Progress 等组件都有用到该组梯度变量。 | string | |
| colorSuccess | 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| colorWarning | 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 | string | |
| lineHeight | 文本行高 | number | |
| lineHeightHeading3 | h3 标签所使用的行高 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingXL | 控制元素的特大内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## segmented-cn
Source: https://ant.design/components/segmented-cn.md
---
category: Components
group: 数据展示
title: Segmented
subtitle: 分段控制器
description: 用于展示多个选项并允许用户选择其中单个选项。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*XJR2TbS1aaQAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*-9tSSoO_MkIAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
自 `antd@4.20.0` 版本开始提供该组件。
## 何时使用 {#when-to-use}
- 用于展示多个选项并允许用户选择其中单个选项;
- 当切换选中选项时,关联区域的内容会发生变化。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
options={['Daily', 'Weekly', 'Monthly', 'Quarterly', 'Yearly']}
onChange={(value) => {
console.log(value); // string
}}
/>
);
export default Demo;
```
### 垂直方向
垂直方向。
```tsx
import React from 'react';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
},
{ value: 'Kanban', icon: },
]}
/>
);
export default Demo;
```
### Block 分段选择器
`block` 属性使其适合父元素宽度。
```tsx
import React from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
options={[123, 456, 'longtext-longtext-longtext-longtext']} block />
);
export default Demo;
```
### 胶囊形状
胶囊型的 Segmented。
```tsx
import React, { useState } from 'react';
import { MoonOutlined, SunOutlined } from '@ant-design/icons';
import { Flex, Segmented } from 'antd';
import type { SizeType } from '../../config-provider/SizeContext';
const Demo: React.FC = () => {
const [size, setSize] = useState('middle');
return (
options={['small', 'middle', 'large']} value={size} onChange={setSize} />
},
{ value: 'dark', icon: },
]}
/>
);
};
export default Demo;
```
### 不可用
Segmented 不可用。
```tsx
import React from 'react';
import { Flex, Segmented } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 受控模式
受控的 Segmented。
```tsx
import React, { useState } from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => {
const [value, setValue] = useState('Map');
return (
options={['Map', 'Transit', 'Satellite']}
value={value}
onChange={setValue}
/>
);
};
export default Demo;
```
### 自定义渲染
自定义渲染每一个 Segmented Item。
```tsx
import React from 'react';
import { UserOutlined } from '@ant-design/icons';
import { Avatar, Flex, Segmented } from 'antd';
const App: React.FC = () => (
User 1
),
value: 'user1',
tooltip: { title: 'hello user1', color: 'gold' },
},
{
label: (
),
value: 'user2',
tooltip: { title: 'hello user2', color: 'pink' },
},
{
label: (
),
value: 'user3',
tooltip: { title: 'hello user3', color: 'geekblue' },
},
]}
/>
Spring
Jan-Mar
),
value: 'spring',
},
{
label: (
),
value: 'summer',
},
{
label: (
),
value: 'autumn',
},
{
label: (
),
value: 'winter',
},
]}
/>
);
export default App;
```
### 动态数据
动态加载数据。
```tsx
import React, { useState } from 'react';
import { Button, Flex, Segmented } from 'antd';
const Demo: React.FC = () => {
const [options, setOptions] = useState(['Daily', 'Weekly', 'Monthly']);
const [moreLoaded, setMoreLoaded] = useState(false);
const handleLoadOptions = () => {
setOptions((prev) => [...prev, 'Quarterly', 'Yearly']);
setMoreLoaded(true);
};
return (
Load more options
);
};
export default Demo;
```
### 三种大小
我们为 ` ` 组件定义了三种尺寸(大、默认、小),高度分别为 `40px`、`32px` 和 `24px`。
```tsx
import React from 'react';
import { Flex, Segmented } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 设置图标
给 Segmented Item 设置 Icon。
```tsx
import React from 'react';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
},
{ label: 'Kanban', value: 'Kanban', icon: },
]}
/>
);
export default Demo;
```
### 只设置图标
在 Segmented Item 选项中只设置 Icon。
```tsx
import React from 'react';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
},
{ value: 'Kanban', icon: },
]}
/>
);
export default Demo;
```
### 配合 name 使用
可以为 Segmented 配置 `name` 参数,为组合内的 input 元素赋予相同的 `name` 属性,使浏览器把 Segmented 下的 input 真正看作是一组(例如可以通过方向键始终**在同一组内**更改选项)。
```tsx
import React from 'react';
import { Segmented } from 'antd';
const Demo: React.FC = () => (
options={['Daily', 'Weekly', 'Monthly', 'Quarterly', 'Yearly']} name="group" />
);
export default Demo;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Segmented 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { CloudOutlined, RocketOutlined, ThunderboltOutlined } from '@ant-design/icons';
import { Flex, Segmented } from 'antd';
import type { SegmentedProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 2px;
`,
}));
const styleFn: SegmentedProps['styles'] = (info) => {
if (info.props.vertical) {
return {
root: {
border: '1px solid #77BEF0',
padding: 4,
width: 100,
},
icon: {
color: '#77BEF0',
},
item: {
textAlign: 'start',
},
} satisfies SegmentedProps['styles'];
}
return {};
};
const styles: SegmentedProps['styles'] = {
root: {
padding: 4,
width: 260,
},
};
const options: SegmentedProps['options'] = [
{
label: 'Boost',
value: 'boost',
icon: ,
},
{
label: 'Stream',
value: 'stream',
icon: ,
},
{
label: 'Cloud',
value: 'cloud',
icon: ,
},
];
const App: React.FC = () => {
const segmentedSharedProps: SegmentedProps = {
options,
classNames,
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> 自 `antd@4.20.0` 版本开始提供该组件。
### Segmented
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| block | 将宽度调整为父元素宽度的选项 | boolean | false | |
| classNames | 用于自定义 Segmented 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| defaultValue | 默认选中的值 | string \| number | | |
| disabled | 是否禁用 | boolean | false | |
| onChange | 选项变化时的回调函数 | function(value: string \| number) | | |
| options | 数据化配置选项内容 | string\[] \| number\[] \| SegmentedItemType\[] | [] | |
| orientation | 排列方向 | `horizontal` \| `vertical` | `horizontal` | |
| size | 控件尺寸 | `large` \| `middle` \| `small` | `middle` | |
| styles | 用于自定义 Segmented 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom) , CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom) , CSSProperties> | - | |
| vertical | 排列方向,与 `orientation` 同时存在,以 `orientation` 优先 | boolean | `false` | 5.21.0 |
| value | 当前选中的值 | string \| number | | |
| shape | 形状 | `default` \| `round` | `default` | 5.24.0 |
| name | Segmented 下所有 `input[type="radio"]` 的 `name` 属性。若未设置,则将回退到随机生成的名称 | string | | 5.23.0 |
### SegmentedItemType
| 属性 | 描述 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| className | 自定义类名 | string | - | |
| disabled | 分段项的禁用状态 | boolean | false | |
| icon | 分段项的显示图标 | ReactNode | - | |
| label | 分段项的显示文本 | ReactNode | - | |
| tooltip | 分段项的工具提示 | string \| [TooltipProps](../tooltip/index.zh-CN.md#api) | - | |
| value | 分段项的值 | string \| number | - | |
## Semantic DOM
https://ant.design/components/segmented-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Segmented)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| itemActiveBg | 选项激活态背景颜色 | string | rgba(0,0,0,0.15) |
| itemColor | 选项文本颜色 | string | rgba(0,0,0,0.65) |
| itemHoverBg | 选项悬浮态背景颜色 | string | rgba(0,0,0,0.06) |
| itemHoverColor | 选项悬浮态文本颜色 | string | rgba(0,0,0,0.88) |
| itemSelectedBg | 选项选中时背景颜色 | string | #ffffff |
| itemSelectedColor | 选项选中时文字颜色 | string | rgba(0,0,0,0.88) |
| trackBg | Segmented 控件容器背景色 | string | #f5f5f5 |
| trackPadding | Segmented 控件容器的 padding | string \| number | 2 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusLG | LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| boxShadowTertiary | 控制元素三级盒子阴影样式。 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| controlPaddingHorizontal | 控制元素水平内间距。 | number | |
| controlPaddingHorizontalSM | 控制元素中小尺寸水平内间距。 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| motionEaseInOut | 预设动效曲率 | string | |
| paddingXXS | 控制元素的极小内间距。 | number | |
---
## select-cn
Source: https://ant.design/components/select-cn.md
---
category: Components
group: 数据录入
title: Select
subtitle: 选择器
description: 下拉选择器。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*qGSbQJ0POEsAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*a6ggRInInJ4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。
- 当选项少时(少于 5 项),建议直接将选项平铺,使用 [Radio](/components/radio-cn/) 是更好的选择。
- 如果你在寻找一个可输可选的输入框,那你可能需要 [AutoComplete](/components/auto-complete-cn/)。
## 代码演示 {#examples}
### 基本使用
基本使用。
```tsx
import React from 'react';
import { Select, Space } from 'antd';
const handleChange = (value: string) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### 带搜索框
展开后可对选项进行搜索。
```tsx
import React from 'react';
import { Select } from 'antd';
const onChange = (value: string) => {
console.log(`selected ${value}`);
};
const onSearch = (value: string) => {
console.log('search:', value);
};
const App: React.FC = () => (
);
export default App;
```
### 自定义搜索
使用 `filterOption` 自定义搜索。
```tsx
import React from 'react';
import { Select } from 'antd';
const App: React.FC = () => (
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
}}
placeholder="Select a person"
options={[
{ value: '1', label: 'Jack' },
{ value: '2', label: 'Lucy' },
{ value: '3', label: 'Tom' },
]}
/>
);
export default App;
```
### 多字段搜索
使用 `optionFilterProp` 多字段搜索。
```tsx
import React from 'react';
import { Select } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 多选
多选,从已有条目中选择。
```tsx
import React from 'react';
import { Select, Space } from 'antd';
import type { SelectProps } from 'antd';
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
label: i.toString(36) + i,
value: i.toString(36) + i,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### 三种大小
三种大小的选择框,当 size 分别为 `large` 和 `small` 时,输入框高度为 `40px` 和 `24px` ,默认高度为 `32px`。
```tsx
import React, { useState } from 'react';
import { Radio, Select, Space } from 'antd';
import type { ConfigProviderProps, RadioChangeEvent, SelectProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
value: i.toString(36) + i,
label: i.toString(36) + i,
});
}
const handleChange = (value: string | string[]) => {
console.log(`Selected: ${value}`);
};
const App: React.FC = () => {
const [size, setSize] = useState('middle');
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
return (
<>
Large
Default
Small
>
);
};
export default App;
```
### 自定义下拉选项
使用 `optionRender` 自定义渲染下拉选项。
```tsx
import React from 'react';
import { Select, Space } from 'antd';
const options = [
{
label: 'Happy',
value: 'happy',
emoji: '😄',
desc: 'Feeling Good',
},
{
label: 'Sad',
value: 'sad',
emoji: '😢',
desc: 'Feeling Blue',
},
{
label: 'Angry',
value: 'angry',
emoji: '😡',
desc: 'Furious',
},
{
label: 'Cool',
value: 'cool',
emoji: '😎',
desc: 'Chilling',
},
{
label: 'Sleepy',
value: 'sleepy',
emoji: '😴',
desc: 'Need Sleep',
},
];
const App: React.FC = () => (
{
console.log(`selected ${value}`);
}}
options={options}
optionRender={(option) => (
{option.data.emoji}
{`${option.data.label} (${option.data.desc})`}
)}
/>
);
export default App;
```
### 带排序的搜索
在搜索模式下对过滤结果项进行排序。
```tsx
import React from 'react';
import { Select } from 'antd';
const App: React.FC = () => (
(optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase()),
}}
style={{ width: 200 }}
placeholder="Search to Select"
options={[
{
value: '1',
label: 'Not Identified',
},
{
value: '2',
label: 'Closed',
},
{
value: '3',
label: 'Communicated',
},
{
value: '4',
label: 'Identified',
},
{
value: '5',
label: 'Resolved',
},
{
value: '6',
label: 'Cancelled',
},
]}
/>
);
export default App;
```
### 标签
标签形式的多选框,用户亦可自由输入。
```tsx
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
value: i.toString(36) + i,
label: i.toString(36) + i,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### 分组
用 `OptGroup` 进行选项分组。
```tsx
import React from 'react';
import { Select } from 'antd';
const handleChange = (value: string) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
manager,
title: 'manager',
options: [
{ label: Jack , value: 'Jack' },
{ label: Lucy , value: 'Lucy' },
],
},
{
label: engineer ,
title: 'engineer',
options: [
{ label: Chloe , value: 'Chloe' },
{ label: Lucas , value: 'Lucas' },
],
},
]}
/>
);
export default App;
```
### 联动
省市联动是典型的例子,联动场景我们更推荐使用 [Cascader](/components/cascader-cn/) 组件。
```tsx
import React, { useState } from 'react';
import { Select, Space } from 'antd';
const cityData = {
Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
};
type CityName = keyof typeof cityData;
const provinceData: CityName[] = ['Zhejiang', 'Jiangsu'];
const App: React.FC = () => {
const [cities, setCities] = useState(cityData[provinceData[0] as CityName]);
const [secondCity, setSecondCity] = useState(cityData[provinceData[0]][0] as CityName);
const handleProvinceChange = (value: CityName) => {
setCities(cityData[value]);
setSecondCity(cityData[value][0] as CityName);
};
const onSecondCityChange = (value: CityName) => {
setSecondCity(value);
};
return (
({ label: province, value: province }))}
/>
({ label: city, value: city }))}
/>
);
};
export default App;
```
### 搜索框
搜索和远程数据结合。
```tsx
import React, { useState } from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
let timeout: ReturnType | null;
let currentValue: string;
const toURLSearchParams = >(record: T) => {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(record)) {
params.append(key, value);
}
return params;
};
const fetchData = (value: string, callback: (data: { value: string; text: string }[]) => void) => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
currentValue = value;
const params = toURLSearchParams({ code: 'utf-8', q: value });
const fake = () => {
fetch(`https://suggest.taobao.com/sug?${params.toString()}`)
.then((response) => response.json())
.then(({ result }) => {
if (currentValue === value) {
const data = result.map((item: any) => ({ value: item[0], text: item[0] }));
callback(data);
}
});
};
if (value) {
timeout = setTimeout(fake, 300);
} else {
callback([]);
}
};
const SearchInput: React.FC<{ placeholder: string; style: React.CSSProperties }> = (props) => {
const [data, setData] = useState([]);
const [value, setValue] = useState();
const handleSearch = (newValue: string) => {
fetchData(newValue, setData);
};
const handleChange = (newValue: string) => {
setValue(newValue);
};
return (
({
value: d.value,
label: d.text,
}))}
/>
);
};
const App: React.FC = () => ;
export default App;
```
### 获得选项的文本
默认情况下 `onChange` 里只能拿到 `value`,如果需要拿到选中的节点文本 `label`,可以使用 `labelInValue` 属性。
选中项的 `label` 会被包装到 `value` 中传递给 `onChange` 等函数,此时 `value` 是一个对象。
```tsx
import React from 'react';
import { Select } from 'antd';
const handleChange = (value: { value: string; label: React.ReactNode }) => {
console.log(value); // { value: "lucy", key: "lucy", label: "Lucy (101)" }
};
const App: React.FC = () => (
);
export default App;
```
### 自动分词
试下复制 `露西,杰克` 并粘贴到输入框里。只在 tags 和 multiple 模式下可用。
```tsx
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
const options: SelectProps['options'] = [];
for (let i = 10; i < 36; i++) {
options.push({
value: i.toString(36) + i,
label: i.toString(36) + i,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### 搜索用户
一个带有远程搜索,防抖控制,请求时序控制,加载状态的多选示例。
```tsx
import React, { useMemo, useRef, useState } from 'react';
import { Avatar, Select, Spin } from 'antd';
import type { SelectProps } from 'antd';
import debounce from 'lodash/debounce';
export interface DebounceSelectProps
extends Omit, 'options' | 'children'> {
fetchOptions: (search: string) => Promise;
debounceTimeout?: number;
}
function DebounceSelect<
ValueType extends {
key?: string;
label: React.ReactNode;
value: string | number;
avatar?: string;
} = any,
>({ fetchOptions, debounceTimeout = 300, ...props }: DebounceSelectProps) {
const [fetching, setFetching] = useState(false);
const [options, setOptions] = useState([]);
const fetchRef = useRef(0);
const debounceFetcher = useMemo(() => {
const loadOptions = (value: string) => {
fetchRef.current += 1;
const fetchId = fetchRef.current;
setOptions([]);
setFetching(true);
fetchOptions(value).then((newOptions) => {
if (fetchId !== fetchRef.current) {
// for fetch callback order
return;
}
setOptions(newOptions);
setFetching(false);
});
};
return debounce(loadOptions, debounceTimeout);
}, [fetchOptions, debounceTimeout]);
return (
: 'No results found'}
{...props}
options={options}
optionRender={(option) => (
{option.data.avatar &&
}
{option.label}
)}
/>
);
}
// Usage of DebounceSelect
interface UserValue {
label: string;
value: string;
avatar?: string;
}
async function fetchUserList(username: string): Promise {
console.log('fetching user', username);
return fetch(`https://660d2bd96ddfa2943b33731c.mockapi.io/api/users/?search=${username}`)
.then((res) => res.json())
.then((res) => {
const results = Array.isArray(res) ? res : [];
return results.map((user) => ({
label: user.name,
value: user.id,
avatar: user.avatar,
}));
})
.catch(() => {
console.log('fetch mock data failed');
return [];
});
}
const App: React.FC = () => {
const [value, setValue] = useState([]);
return (
{
if (Array.isArray(newValue)) {
setValue(newValue);
}
}}
/>
);
};
export default App;
```
### 前后缀
自定义前缀 `prefix` 和后缀图标 `suffixIcon`。
```tsx
import React from 'react';
import { MehOutlined, SmileOutlined } from '@ant-design/icons';
import { Select, Space } from 'antd';
const smileIcon = ;
const mehIcon = ;
const handleChange = (value: string | string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
);
export default App;
```
### 扩展菜单
使用 `popupRender` 对下拉菜单进行自由扩展。如果希望点击自定义内容后关闭浮层,你需要使用受控模式自行控制([codesandbox](https://codesandbox.io/s/ji-ben-shi-yong-antd-4-21-7-forked-gnp4cy?file=/demo.js))。
```tsx
import React, { useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Input, Select, Space } from 'antd';
import type { InputRef } from 'antd';
let index = 0;
const App: React.FC = () => {
const [items, setItems] = useState(['jack', 'lucy']);
const [name, setName] = useState('');
const inputRef = useRef(null);
const onNameChange = (event: React.ChangeEvent) => {
setName(event.target.value);
};
const addItem = (e: React.MouseEvent) => {
e.preventDefault();
setItems([...items, name || `New item ${index++}`]);
setName('');
setTimeout(() => {
inputRef.current?.focus();
}, 0);
};
return (
(
<>
{menu}
e.stopPropagation()}
/>
} onClick={addItem}>
Add item
>
)}
options={items.map((item) => ({ label: item, value: item }))}
/>
);
};
export default App;
```
### 隐藏已选择选项
隐藏下拉列表中已选择的选项。
```tsx
import React, { useState } from 'react';
import { Select } from 'antd';
const OPTIONS = ['Apples', 'Nails', 'Bananas', 'Helicopters'];
const App: React.FC = () => {
const [selectedItems, setSelectedItems] = useState([]);
const filteredOptions = OPTIONS.filter((o) => !selectedItems.includes(o));
return (
({
value: item,
label: item,
}))}
/>
);
};
export default App;
```
### 形态变体
Select 形态变体,可选 `outlined` `filled` `borderless` `underlined` 四种形态。
```tsx
import React from 'react';
import { Flex, Select } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 自定义选择标签
允许自定义选择标签的样式。
```tsx
import React from 'react';
import { Select, Tag } from 'antd';
import type { SelectProps } from 'antd';
type TagRender = SelectProps['tagRender'];
const options: SelectProps['options'] = [
{ value: 'gold' },
{ value: 'lime' },
{ value: 'green' },
{ value: 'cyan' },
];
const tagRender: TagRender = (props) => {
const { label, value, closable, onClose } = props;
const onPreventMouseDown = (event: React.MouseEvent) => {
event.preventDefault();
event.stopPropagation();
};
return (
{label}
);
};
const App: React.FC = () => (
);
export default App;
```
### 自定义选中 label
允许自定义渲染当前选中的 label, 可用于 value 回填但对应选项缺失而不想直接渲染 value 的场景。
```tsx
import React from 'react';
import { Select } from 'antd';
import type { SelectProps } from 'antd';
type LabelRender = SelectProps['labelRender'];
const options = [
{ label: 'gold', value: 'gold' },
{ label: 'lime', value: 'lime' },
{ label: 'green', value: 'green' },
{ label: 'cyan', value: 'cyan' },
];
const labelRender: LabelRender = (props) => {
const { label, value } = props;
if (label) {
return value;
}
return No option match ;
};
const App: React.FC = () => (
);
export default App;
```
### 响应式 maxTagCount
多选下通过响应式布局让选项自动收缩。该功能对性能有所消耗,不推荐在大表单场景下使用。
```tsx
import React, { useState } from 'react';
import type { SelectProps } from 'antd';
import { Select, Space, Tooltip } from 'antd';
interface ItemProps {
label: string;
value: string;
}
const options: ItemProps[] = [];
for (let i = 10; i < 36; i++) {
const value = i.toString(36) + i;
options.push({
label: `Long Label: ${value}`,
value,
});
}
const sharedProps: SelectProps = {
mode: 'multiple',
style: { width: '100%' },
options,
placeholder: 'Select Item...',
maxTagCount: 'responsive',
};
const App: React.FC = () => {
const [value, setValue] = useState(['a10', 'c12', 'h17', 'j19', 'k20']);
const selectProps: SelectProps = {
value,
onChange: setValue,
};
return (
(
label).join(', ')}
>
Hover Me
)}
/>
);
};
export default App;
```
### 大数据
Select 默认针对大数据开启了[虚拟滚动](https://github.com/react-component/virtual-list),因而获得了更好的性能,可以通过 `virtual={false}` 关闭。
```tsx
import React from 'react';
import type { SelectProps } from 'antd';
import { Select, Typography } from 'antd';
const { Title } = Typography;
const options: SelectProps['options'] = [];
for (let i = 0; i < 100000; i++) {
const value = `${i.toString(36)}${i}`;
options.push({
label: value,
value,
disabled: i === 10,
});
}
const handleChange = (value: string[]) => {
console.log(`selected ${value}`);
};
const App: React.FC = () => (
<>
{options.length} Items
>
);
export default App;
```
### 自定义状态
使用 `status` 为 Select 添加状态,可选 `error` 或者 `warning`。
```tsx
import React from 'react';
import { Select, Space } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 弹出位置
可以通过 `placement` 手动指定弹出的位置。
```tsx
import React, { useState } from 'react';
import type { RadioChangeEvent, SelectProps } from 'antd';
import { Radio, Select } from 'antd';
type SelectCommonPlacement = SelectProps['placement'];
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;
```
### 最大选中数量
你可以通过设置 `maxCount` 约束最多可选中的数量,当超出限制时会变成禁止选中状态。
```tsx
import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Select } from 'antd';
const MAX_COUNT = 3;
const App: React.FC = () => {
const [value, setValue] = React.useState(['Ava Swift']);
const suffix = (
<>
{value.length} / {MAX_COUNT}
>
);
return (
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Select 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { MehOutlined } from '@ant-design/icons';
import { Flex, Select } from 'antd';
import type { SelectProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border-radius: 8px;
width: 300px;
`,
}));
const options: SelectProps['options'] = [
{ value: 'GuangZhou', label: 'GuangZhou' },
{ value: 'ShenZhen', label: 'ShenZhen' },
];
const stylesObject: SelectProps['styles'] = {
prefix: {
color: '#1890ff',
},
suffix: {
color: '#1890ff',
},
};
const stylesFn: SelectProps['styles'] = (info) => {
const { props } = info;
if (props.variant === 'filled') {
return {
prefix: {
color: '#722ed1',
},
suffix: {
color: '#722ed1',
},
popup: {
root: {
border: '1px solid #722ed1',
},
},
} satisfies SelectProps['styles'];
}
return {};
};
const App: React.FC = () => {
const sharedProps: SelectProps = {
options,
classNames,
prefix: ,
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Select props
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| allowClear | 自定义清除按钮 | boolean \| { clearIcon?: ReactNode } | false | 5.8.0: 支持对象类型 |
| ~~autoClearSearchValue~~ | 是否在选中项后清空搜索框,只在 `mode` 为 `multiple` 或 `tags` 时有效 | boolean | true | |
| classNames | 用于自定义 Select 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| defaultActiveFirstOption | 是否默认高亮第一个选项 | boolean | true | |
| defaultOpen | 是否默认展开下拉菜单 | boolean | - | |
| defaultValue | 指定默认选中的条目 | string \| string\[] \| number \| number\[] \| LabeledValue \| LabeledValue\[] | - | |
| disabled | 是否禁用 | boolean | false | |
| ~~popupClassName~~ | 下拉菜单的 className 属性,使用 `classNames.popup.root` 替换 | string | - | 4.23.0 |
| popupMatchSelectWidth | 下拉菜单和选择器同宽。默认将设置 `min-width`,当值小于选择框宽度时会被忽略。false 时会关闭虚拟滚动 | boolean \| number | true | 5.5.0 |
| ~~dropdownRender~~ | 自定义下拉框内容,使用 `popupRender` 替换 | (originNode: ReactNode) => ReactNode | - | |
| popupRender | 自定义下拉框内容 | (originNode: ReactNode) => ReactNode | - | 5.25.0 |
| ~~dropdownStyle~~ | 下拉菜单的 style 属性,使用 `styles.popup.root` 替换 | CSSProperties | - | |
| fieldNames | 自定义节点 label、value、options、groupLabel 的字段 | object | { label: `label`, value: `value`, options: `options`, groupLabel: `label` } | 4.17.0(`groupLabel` 在 5.6.0 新增) |
| ~~filterOption~~ | 是否根据输入项进行筛选。当其为一个函数时,会接收 `inputValue` `option` 两个参数,当 `option` 符合筛选条件时,应返回 true,反之则返回 false。[示例](#select-demo-search) | boolean \| function(inputValue, option) | true | |
| ~~filterSort~~ | 搜索时对筛选结果项的排序函数, 类似[Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)里的 compareFunction | (optionA: Option, optionB: Option, info: { searchValue: string }) => number | - | `searchValue`: 5.19.0 |
| getPopupContainer | 菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。[示例](https://codesandbox.io/s/4j168r7jw0) | function(triggerNode) | () => document.body | |
| labelInValue | 是否把每个选项的 label 包装到 value 中,会把 Select 的 value 类型从 `string` 变为 { value: string, label: ReactNode } 的格式 | boolean | false | |
| listHeight | 设置弹窗滚动高度 | number | 256 | |
| loading | 加载中状态 | boolean | false | |
| maxCount | 指定可选中的最多 items 数量,仅在 `mode` 为 `multiple` 或 `tags` 时生效 | number | - | 5.13.0 |
| maxTagCount | 最多显示多少个 tag,响应式模式会对性能产生损耗 | number \| `responsive` | - | responsive: 4.10 |
| maxTagPlaceholder | 隐藏 tag 时显示的内容 | ReactNode \| function(omittedValues) | - | |
| maxTagTextLength | 最大显示的 tag 文本长度 | number | - | |
| menuItemSelectedIcon | 自定义多选时当前选中的条目图标 | ReactNode | - | |
| mode | 设置 Select 的模式为多选或标签 | `multiple` \| `tags` | - | |
| notFoundContent | 当下拉列表为空时显示的内容 | ReactNode | `Not Found` | |
| open | 是否展开下拉菜单 | boolean | - | |
| ~~optionFilterProp~~ | 已废弃,见 `showSearch.optionFilterProp` | | | |
| optionLabelProp | 回填到选择框的 Option 的属性值,默认是 Option 的子元素。比如在子元素需要高亮效果时,此值可以设为 `value`。[示例](https://codesandbox.io/s/antd-reproduction-template-tk678) | string | `children` | |
| options | 数据化配置选项内容,相比 jsx 定义会获得更好的渲染性能 | { label, value }\[] | - | |
| optionRender | 自定义渲染下拉选项 | (option: FlattenOptionData\ , info: { index: number }) => React.ReactNode | - | 5.11.0 |
| placeholder | 选择框默认文本 | string | - | |
| placement | 选择框弹出的位置 | `bottomLeft` `bottomRight` `topLeft` `topRight` | bottomLeft | |
| prefix | 自定义前缀 | ReactNode | - | 5.22.0 |
| removeIcon | 自定义的多选框清除图标 | ReactNode | - | |
| ~~searchValue~~ | 控制搜索文本 | string | - | |
| showSearch | 配置是否可搜索 | boolean \| [Object](#showsearch) | 单选为 false,多选为 true | |
| size | 选择框大小 | `large` \| `middle` \| `small` | `middle` | |
| status | 设置校验状态 | 'error' \| 'warning' | - | 4.19.0 |
| styles | 用于自定义 Select 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| suffixIcon | 自定义的选择框后缀图标。以防止图标被用于其他交互,替换的图标默认不会响应展开、收缩事件,可以通过添加 `pointer-events: none` 样式透传。 | ReactNode | ` ` | |
| tagRender | 自定义 tag 内容 render,仅在 `mode` 为 `multiple` 或 `tags` 时生效 | (props) => ReactNode | - | |
| labelRender | 自定义当前选中的 label 内容 render (LabelInValueType的定义见 [LabelInValueType](https://github.com/react-component/select/blob/b39c28aa2a94e7754ebc570f200ab5fd33bd31e7/src/Select.tsx#L70)) | (props: LabelInValueType) => ReactNode | - | 5.15.0 |
| tokenSeparators | 自动分词的分隔符,仅在 `mode="tags"` 时生效 | string\[] | - | |
| value | 指定当前选中的条目,多选时为一个数组。(value 数组引用未变化时,Select 不会更新) | string \| string\[] \| number \| number\[] \| LabeledValue \| LabeledValue\[] | - | |
| variant | 形态变体 | `outlined` \| `borderless` \| `filled` \| `underlined` | `outlined` | 5.13.0 \| `underlined`: 5.24.0 |
| virtual | 设置 false 时关闭虚拟滚动 | boolean | true | 4.1.0 |
| onActive | 键盘和鼠标交互时触发 | function(value: string \| number \| LabeledValue) | - | |
| onBlur | 失去焦点时回调 | function | - | |
| onChange | 选中 option,或 input 的 value 变化时,调用此函数 | function(value, option:Option \| Array<Option>) | - | |
| onClear | 清除内容时回调 | function | - | 4.6.0 |
| onDeselect | 取消选中时调用,参数为选中项的 value (或 key) 值,仅在 `multiple` 或 `tags` 模式下生效 | function(value: string \| number \| LabeledValue) | - | |
| ~~onDropdownVisibleChange~~ | 展开下拉菜单的回调,使用 `onOpenChange` 替换 | (open: boolean) => void | - | |
| onOpenChange | 展开下拉菜单的回调 | (open: boolean) => void | - | |
| onFocus | 获得焦点时回调 | (event: FocusEvent) => void | - | |
| onInputKeyDown | 按键按下时回调 | (event: KeyboardEvent) => void | - | |
| onPopupScroll | 下拉列表滚动时的回调 | (event: UIEvent) => void | - | |
| ~~onSearch~~ | 文本框值变化时回调 | function(value: string) | - | |
| onSelect | 被选中时调用,参数为选中项的 value (或 key) 值 | function(value: string \| number \| LabeledValue, option: Option) | - | |
> 注意,如果发现下拉菜单跟随页面滚动,或者需要在其他弹层中触发 Select,请尝试使用 `getPopupContainer={triggerNode => triggerNode.parentElement}` 将下拉弹层渲染节点固定在触发器的父元素中。
### showSearch
| Property | Description | Type | Default | Version |
| --- | --- | --- | --- | --- |
| autoClearSearchValue | 是否在选中项后清空搜索框,只在 `mode` 为 `multiple` 或 `tags` 时有效 | boolean | true | |
| filterOption | 是否根据输入项进行筛选。当其为一个函数时,会接收 `inputValue` `option` 两个参数,当 `option` 符合筛选条件时,应返回 true,反之则返回 false。[示例](#select-demo-search) | boolean \| function(inputValue, option) | true | |
| filterSort | 搜索时对筛选结果项的排序函数, 类似[Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)里的 compareFunction | (optionA: Option, optionB: Option, info: { searchValue: string }) => number | - | `searchValue`: 5.19.0 |
| optionFilterProp | 搜索时过滤对应的 `option` 属性,如设置为 `children` 表示对内嵌内容进行搜索。 若通过 `options` 属性配置选项内容,建议设置 `optionFilterProp="label"` 来对内容进行搜索。 当传入 `string[]` 时多个字段进行 OR 匹配搜索 | string \| string[] | `value` | `string[]`: 6.1.0 |
| searchValue | 控制搜索文本 | string | - | |
| onSearch | 文本框值变化时回调 | function(value: string) | - | |
### Select Methods
| 名称 | 说明 | 版本 |
| ------- | -------- | ---- |
| blur() | 取消焦点 | |
| focus() | 获取焦点 | |
### Option props
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------- | ------------------------ | ---------------- | ------ | ---- |
| className | Option 器类名 | string | - | |
| disabled | 是否禁用 | boolean | false | |
| title | 选项上的原生 title 提示 | string | - | |
| value | 默认根据此属性值进行筛选 | string \| number | - | |
### OptGroup props
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --------- | ----------------------- | --------------- | ------ | ---- |
| key | Key | string | - | |
| label | 组名 | React.ReactNode | - | |
| className | Option 器类名 | string | - | |
| title | 选项上的原生 title 提示 | string | - | |
## Semantic DOM
https://ant.design/components/select-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 | |
| colorBgBase | 用于派生背景色梯度的基础变量,v5 中我们添加了一层背景色的派生算法可以产出梯度明确的背景色的梯度变量。但请不要在代码中直接使用该 Seed Token ! | string | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgContainerDisabled | 控制容器在禁用状态下的背景色。 | string | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorBorder | 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 | string | |
| colorBorderDisabled | 控制元素在禁用状态下的边框颜色。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBgHover | 错误色的浅色背景色悬浮态 | string | |
| colorErrorHover | 错误色的深色悬浮态 | string | |
| colorErrorOutline | 控制输入组件错误状态下的外轮廓线颜色。 | 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 | |
| colorWarningBg | 警戒色的浅色背景颜色 | string | |
| colorWarningBgHover | 警戒色的浅色背景色悬浮态 | string | |
| colorWarningHover | 警戒色的深色悬浮态 | string | |
| colorWarningOutline | 控制输入组件警告状态下的外轮廓线颜色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| 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
### `mode="tags"` 模式下为何搜索有时会出现两个相同选项? {#faq-tags-mode-duplicate}
这一般是 `options` 中的 `label` 和 `value` 不同导致的,你可以通过 `optionFilterProp="label"` 将过滤设置为展示值以避免这种情况。
### 点击 `popupRender` 里的元素,下拉菜单不会自动消失? {#faq-popup-not-close}
你可以使用受控模式,手动设置 `open` 属性:[codesandbox](https://codesandbox.io/s/ji-ben-shi-yong-antd-4-21-7-forked-gnp4cy?file=/demo.js)。
### 反过来希望点击 `popupRender` 里元素不消失该怎么办? {#faq-popup-keep-open}
Select 当失去焦点时会关闭下拉框,如果你可以通过阻止默认行为避免丢失焦点导致的关闭:
```tsx
(
{
e.preventDefault();
e.stopPropagation();
}}
>
Some Content
)}
/>
```
### 自定义 Option 样式导致滚动异常怎么办? {#faq-custom-option-scroll}
这是由于虚拟滚动默认选项高度为 `24px`,如果你的选项高度小于该值则需要通过 `listItemHeight` 属性调整,而 `listHeight` 用于设置滚动容器高度:
```tsx
```
注意:`listItemHeight` 和 `listHeight` 为内部属性,如无必要,请勿修改该值。
### 为何无障碍测试会报缺失 `aria-` 属性? {#faq-aria-attribute}
Select 无障碍辅助元素仅在弹窗展开时创建,因而当你在进行无障碍检测时请先打开下拉后再进行测试。对于 `aria-label` 与 `aria-labelledby` 属性缺失警告,请自行为 Select 组件添加相应无障碍属性。
Select 虚拟滚动会模拟无障碍绑定元素。如果需要读屏器完整获取全部列表,你可以设置 `virtual={false}` 关闭虚拟滚动,无障碍选项将会绑定到真实元素上。
### 使用 `tagRender` 生成的自定义标签,点击关闭时会呼出下拉框 {#faq-tagrender-dropdown}
如果你不希望点击某个元素后下拉框自动出现(例如关闭按钮),可以在其上阻止 `MouseDown` 事件的传播。
```tsx
{
const { closable, label, onClose } = props;
return (
{label}
{closable ? (
e.stopPropagation()}
onClick={onClose}
className="cursor-pointer"
>
❎
) : null}
);
}}
/>
```
---
## skeleton-cn
Source: https://ant.design/components/skeleton-cn.md
---
category: Components
group: 反馈
title: Skeleton
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
---
## 何时使用 {#when-to-use}
- 网络较慢,需要长时间等待加载处理的情况下。
- 图文信息内容较多的列表/卡片中。
- 只在第一次加载数据的时候使用。
- 可以被 Spin 完全代替,但是在可用的场景下可以比 Spin 提供更好的视觉效果和用户体验。
## 代码演示 {#examples}
### 基本
最简单的占位效果。
```tsx
import React from 'react';
import { Skeleton } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 复杂的组合
更复杂的组合。
```tsx
import React from 'react';
import { Skeleton } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 动画效果
显示动画效果。
```tsx
import React from 'react';
import { Skeleton } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 按钮/头像/输入框/图像/自定义节点
骨架按钮、头像、输入框、图像和自定义节点。
```tsx
import React, { useState } from 'react';
import { DotChartOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Divider, Flex, Form, Radio, Skeleton, Space, Switch } from 'antd';
type SizeType = 'default' | 'small' | 'large';
type ButtonShapeType = 'circle' | 'square' | 'round' | 'default';
type AvatarShapeType = 'circle' | 'square';
const App: React.FC = () => {
const [active, setActive] = useState(false);
const [block, setBlock] = useState(false);
const [size, setSize] = useState('default');
const [buttonShape, setButtonShape] = useState('default');
const [avatarShape, setAvatarShape] = useState('circle');
const handleActiveChange = (checked: boolean) => {
setActive(checked);
};
const handleBlockChange = (checked: boolean) => {
setBlock(checked);
};
const handleSizeChange = (e: RadioChangeEvent) => {
setSize(e.target.value);
};
const handleShapeButton = (e: RadioChangeEvent) => {
setButtonShape(e.target.value);
};
const handleAvatarShape = (e: RadioChangeEvent) => {
setAvatarShape(e.target.value);
};
return (
Default
Large
Small
Default
Square
Round
Circle
Square
Circle
);
};
export default App;
```
### 包含子组件
加载占位图包含子组件。
```tsx
import React, { useState } from 'react';
import { Button, Skeleton, Space } from 'antd';
const App: React.FC = () => {
const [loading, setLoading] = useState(false);
const showSkeleton = () => {
setLoading(true);
setTimeout(() => {
setLoading(false);
}, 3000);
};
return (
Ant Design, a design language
We supply a series of design principles, practical patterns and high quality design
resources (Sketch and Axure), to help people create their product prototypes beautifully
and efficiently.
Show Skeleton
);
};
export default App;
```
### 列表
在列表组件中使用加载占位符。
```tsx
import React, { useState } from 'react';
import type Icon from '@ant-design/icons';
import { LikeOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import { Avatar, List, Skeleton, Switch } from 'antd';
interface IconTextProps {
icon: typeof Icon;
text: React.ReactNode;
}
const listData = Array.from({ length: 3 }).map((_, i) => ({
href: 'https://ant.design',
title: `ant design part ${i + 1}`,
avatar: `https://api.dicebear.com/7.x/miniavs/svg?seed=${i}`,
description:
'Ant Design, a design language for background applications, is refined by Ant UED Team.',
content:
'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
}));
const IconText: React.FC = ({ icon, text }) => (
<>
{React.createElement(icon, { style: { marginInlineEnd: 8 } })}
{text}
>
);
const App: React.FC = () => {
const [loading, setLoading] = useState(true);
const onChange = (checked: boolean) => {
setLoading(!checked);
};
return (
<>
(
,
,
,
]
: undefined
}
extra={
!loading && (
)
}
>
}
title={{item.title} }
description={item.description}
/>
{item.content}
)}
/>
>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象或者函数可以自定义 Skeleton 组件的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Skeleton } from 'antd';
import type { SkeletonProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classnames = createStaticStyles(({ css }) => ({
root: css`
border-radius: 10px;
padding: 12px;
`,
header: css`
margin-bottom: 12px;
`,
}));
const paragraphStyles = createStaticStyles(({ css }) => ({
paragraph: css`
& > li {
background-color: rgba(229, 243, 254, 0.5);
}
`,
}));
const styles: SkeletonProps['styles'] = {
avatar: {
border: '1px solid #aaa',
},
title: {
border: '1px solid #aaa',
},
};
const stylesFn: SkeletonProps['styles'] = (info) => {
if (info.props.active) {
return {
root: {
border: '1px solid rgba(229, 243, 254, 0.3)',
},
title: {
backgroundColor: 'rgba(229, 243, 254, 0.5)',
height: 20,
borderRadius: 20,
},
} satisfies SkeletonProps['styles'];
}
return {};
};
const App: React.FC = () => {
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### 共同的 API
### Skeleton
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| avatar | 是否显示头像占位图 | boolean \| [SkeletonAvatar](#skeletonavatar) | false | |
| loading | 为 true 时,显示占位图。反之则直接展示子组件 | boolean | - | |
| paragraph | 是否显示段落占位图 | boolean \| [SkeletonParagraphProps](#skeletonparagraphprops) | true | |
| round | 为 true 时,段落和标题显示圆角 | boolean | false | |
| title | 是否显示标题占位图 | boolean \| [SkeletonTitleProps](#skeletontitleprops) | true | |
#### SkeletonTitleProps
| 属性 | 说明 | 类型 | 默认值 |
| ----- | -------------------- | ---------------- | ------ |
| width | 设置标题占位图的宽度 | number \| string | - |
#### SkeletonParagraphProps
| 属性 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| rows | 设置段落占位图的行数 | number | - |
| width | 设置段落占位图的宽度,若为数组时则为对应的每行宽度,反之则是最后一行的宽度 | number \| string \| Array<number \| string> | - |
### Skeleton.Avatar
| 属性 | 说明 | 类型 | 默认值 |
| ----- | -------------------- | ----------------------------------------- | --------- |
| shape | 指定头像的形状 | `circle` \| `square` | `circle` |
| size | 设置头像占位图的大小 | number \| `large` \| `small` \| `default` | `default` |
### Skeleton.Button
| 属性 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| block | 将按钮宽度调整为其父宽度的选项 | boolean | false | 4.17.0 |
| shape | 指定按钮的形状 | `circle` \| `round` \| `square` \| `default` | - | |
| size | 设置按钮的大小 | `large` \| `small` \| `default` | - | |
### Skeleton.Input
| 属性 | 说明 | 类型 | 默认值 |
| ---- | ---------------- | ------------------------------- | ------ |
| size | 设置输入框的大小 | `large` \| `small` \| `default` | - |
## Semantic DOM
### Skeleton
https://ant.design/components/skeleton-cn/semantic.md
### Skeleton.Element
https://ant.design/components/skeleton-cn/semantic_element.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Skeleton)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| blockRadius | 骨架屏圆角 | number | 4 |
| gradientFromColor | 渐变色起点颜色 | string | rgba(0,0,0,0.06) |
| gradientToColor | 渐变色终点颜色 | string | rgba(0,0,0,0.15) |
| paragraphLiHeight | 段落骨架屏单行高度 | number | 16 |
| paragraphMarginTop | 段落骨架屏上间距 | number | 28 |
| titleHeight | 标题骨架屏高度 | string \| number | 16 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| controlHeightSM | 较小的组件高度 | number | |
| controlHeightXS | 更小的组件高度 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| padding | 控制元素的内间距。 | number | |
---
## slider-cn
Source: https://ant.design/components/slider-cn.md
---
category: Components
group: 数据录入
title: Slider
subtitle: 滑动输入条
description: 滑动型输入器,展示当前值和可选范围。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*_4heQaUrFn4AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*XkgXTaudeosAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
当用户需要在数值区间/自定义区间内进行选择时,可为连续或离散值。
## 代码演示 {#examples}
### 基本
基本滑动条。当 `range` 为 `true` 时,渲染为双滑块。当 `disabled` 为 `true` 时,滑块处于不可用状态。
```tsx
import React, { useState } from 'react';
import { Slider, Switch } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(false);
const onChange = (checked: boolean) => {
setDisabled(checked);
};
return (
<>
Disabled:
>
);
};
export default App;
```
### 带输入框的滑块
和 [数字输入框](/components/input-number-cn) 组件保持同步。
```tsx
import React, { useState } from 'react';
import type { InputNumberProps } from 'antd';
import { Col, InputNumber, Row, Slider, Space } from 'antd';
const IntegerStep: React.FC = () => {
const [inputValue, setInputValue] = useState(1);
const onChange: InputNumberProps['onChange'] = (newValue) => {
setInputValue(newValue as number);
};
return (
);
};
const DecimalStep: React.FC = () => {
const [inputValue, setInputValue] = useState(0);
const onChange: InputNumberProps['onChange'] = (value) => {
if (Number.isNaN(value)) {
return;
}
setInputValue(value as number);
};
return (
);
};
const App: React.FC = () => (
);
export default App;
```
### 带 icon 的滑块
滑块左右可以设置图标来表达业务含义。
```tsx
import React, { useState } from 'react';
import { FrownOutlined, SmileOutlined } from '@ant-design/icons';
import { Slider } from 'antd';
interface IconSliderProps {
max: number;
min: number;
}
const IconSlider: React.FC = (props) => {
const { max, min } = props;
const [value, setValue] = useState(0);
const mid = Number(((max - min) / 2).toFixed(5));
const preColorCls = value >= mid ? '' : 'icon-wrapper-active';
const nextColorCls = value >= mid ? 'icon-wrapper-active' : '';
return (
);
};
const App: React.FC = () => ;
export default App;
```
### 自定义提示
使用 `tooltip.formatter` 可以格式化 `Tooltip` 的内容,设置 `tooltip.formatter={null}`,则隐藏 `Tooltip`。
```tsx
import React from 'react';
import type { SliderSingleProps } from 'antd';
import { Slider } from 'antd';
const formatter: NonNullable['formatter'] = (value) => `${value}%`;
const App: React.FC = () => (
<>
>
);
export default App;
```
### 事件
当 Slider 的值发生改变时,会触发 `onChange` 事件,并把改变后的值作为参数传入。在 `mouseup` 或者 `keyup` 时,会触发 `onChangeComplete` 事件,并把当前值作为参数传入。
```tsx
import React from 'react';
import { Slider } from 'antd';
const onChange = (value: number | number[]) => {
console.log('onChange: ', value);
};
const onChangeComplete = (value: number | number[]) => {
console.log('onChangeComplete: ', value);
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### 带标签的滑块
使用 `marks` 属性标注分段式滑块,使用 `value` / `defaultValue` 指定滑块位置。当 `included=false` 时,表明不同标记间为并列关系。当 `step=null` 时,Slider 的可选值仅有 `marks` 标出来的部分。
```tsx
import React from 'react';
import { Slider } from 'antd';
import type { SliderSingleProps } from 'antd';
const marks: SliderSingleProps['marks'] = {
0: '0°C',
26: '26°C',
37: '37°C',
100: {
style: {
color: '#f50',
},
label: 100°C ,
},
};
const App: React.FC = () => (
<>
included=true
included=false
marks & step
step=null
>
);
export default App;
```
### 垂直
垂直方向的 Slider。
```tsx
import React from 'react';
import { Slider } from 'antd';
import type { SliderSingleProps } from 'antd';
const style: React.CSSProperties = {
display: 'inline-block',
height: 300,
marginInlineStart: 70,
};
const marks: SliderSingleProps['marks'] = {
0: '0°C',
26: '26°C',
37: '37°C',
100: {
style: { color: '#f50' },
label: 100°C ,
},
};
const App: React.FC = () => (
<>
>
);
export default App;
```
### 控制 ToolTip 的显示
当 `tooltip.open` 为 `true` 时,将始终显示 ToolTip;反之则始终不显示,即使在拖动、移入时也是如此。
```tsx
import React from 'react';
import { Slider } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 反向
设置 `reverse` 可以将滑动条置反。
```tsx
import React, { useState } from 'react';
import { Slider, Switch } from 'antd';
const App: React.FC = () => {
const [reverse, setReverse] = useState(true);
return (
<>
Reversed:
>
);
};
export default App;
```
### 范围可拖拽
可以设置 `range.draggableTrack`,使得范围刻度整体可拖拽。
```tsx
import React from 'react';
import { Slider } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 多点组合
范围多个点组合。
```tsx
import React from 'react';
import { Slider } from 'antd';
function getGradientColor(percentage: number) {
const startColor = [135, 208, 104];
const endColor = [255, 204, 199];
const midColor = startColor.map((start, i) => {
const end = endColor[i];
const delta = end - start;
return (start + delta * percentage).toFixed(0);
});
return `rgb(${midColor.join(',')})`;
}
const App: React.FC = () => {
const [value, setValue] = React.useState([0, 10, 20]);
const start = value[0] / 100;
const end = value[value.length - 1] / 100;
return (
);
};
export default App;
```
### 动态增减节点
点击添加节点,拖出或者按键删除节点。
```tsx
import React from 'react';
import { Slider } from 'antd';
const App: React.FC = () => {
const [value, setValue] = React.useState([20, 80]);
return (
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Sliders 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Slider } from 'antd';
import type { SliderSingleProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
width: 300px;
`,
}));
const classNamesFn = createStaticStyles(({ css, cssVar }) => ({
root: css`
width: 100px;
&:hover .ant-slider-handle:after {
box-shadow: 0 0 0 ${cssVar.lineWidthBold} #722ed1;
}
`,
handle: css`
&.ant-slider-handle:hover::after,
&.ant-slider-handle:active::after,
&.ant-slider-handle:focus::after,
&.ant-slider-handle::after {
box-shadow: 0 0 0 ${cssVar.lineWidthBold} #722ed1;
}
`,
}));
const stylesObject: SliderSingleProps['styles'] = {
track: { backgroundImage: 'linear-gradient(180deg, #91caff, #1677ff)' },
handle: { borderColor: '#1677ff', boxShadow: '0 2px 8px #1677ff' },
};
const stylesFn: SliderSingleProps['styles'] = (info) => {
if (info.props.orientation === 'vertical') {
return {
root: { height: 300 },
track: { backgroundImage: 'linear-gradient(180deg, #722cc0, #722ed1)' },
handle: { borderColor: '#722ed1', boxShadow: '0 2px 8px #722ed1' },
} satisfies SliderSingleProps['styles'];
}
return {};
};
const App: React.FC = () => {
const sharedProps: SliderSingleProps = {
defaultValue: 30,
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| defaultValue | 设置初始取值。当 `range` 为 false 时,使用 number,否则用 \[number, number] | number \| \[number, number] | 0 \| \[0, 0] | |
| disabled | 值为 true 时,滑块为禁用状态 | boolean | false | |
| keyboard | 支持使用键盘操作 handler | boolean | true | 5.2.0+ |
| dots | 是否只能拖拽到刻度上 | boolean | false | |
| included | `marks` 不为空对象时有效,值为 true 时表示值为包含关系,false 表示并列 | boolean | true | |
| marks | 刻度标记,key 的类型必须为 `number` 且取值在闭区间 \[min, max] 内,每个标签可以单独设置样式 | object | { number: ReactNode } or { number: { style: CSSProperties, label: ReactNode } } | |
| max | 最大值 | number | 100 | |
| min | 最小值 | number | 0 | |
| orientation | 排列方向 | `horizontal` \| `vertical` | `horizontal` | |
| range | 双滑块模式 | boolean \| [range](#range) | false | |
| reverse | 反向坐标轴 | boolean | false | |
| step | 步长,取值必须大于 0,并且可被 (max - min) 整除。当 `marks` 不为空对象时,可以设置 `step` 为 null,此时 Slider 的可选值仅有 `marks`、`min` 和 `max` | number \| null | 1 | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| tooltip | 设置 Tooltip 相关属性 | [tooltip](#tooltip) | - | 4.23.0 |
| value | 设置当前取值。当 `range` 为 false 时,使用 number,否则用 \[number, number] | number \| \[number, number] | - | |
| vertical | 值为 true 时,Slider 为垂直方向。与 `orientation` 同时存在,以 `orientation` 优先 | boolean | false | |
| onChangeComplete | 与 `mouseup` 和 `keyup` 触发时机一致,把当前值作为参数传入 | (value) => void | - | |
| onChange | 当 Slider 的值发生改变时,会触发 onChange 事件,并把改变后的值作为参数传入 | (value) => void | - | |
### range
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| -------------- | -------------------------------------------------- | ------- | ------ | ------ |
| draggableTrack | 范围刻度是否可被拖拽 | boolean | false | |
| editable | 启动动态增减节点,不能和 `draggableTrack` 一同使用 | boolean | false | 5.20.0 |
| minCount | 配置 `editable` 时,最小节点数量 | number | 0 | 5.20.0 |
| maxCount | 配置 `editable` 时,最大节点数量 | number | - | 5.20.0 |
### tooltip
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| autoAdjustOverflow | 是否自动调整弹出位置 | boolean | true | 5.8.0 |
| open | 值为 true 时,Tooltip 将会始终显示;否则始终不显示,哪怕在拖拽及移入时 | boolean | - | 4.23.0 |
| placement | 设置 Tooltip 展示位置。参考 [Tooltip](/components/tooltip-cn) | string | - | 4.23.0 |
| getPopupContainer | Tooltip 渲染父节点,默认渲染到 body 上 | (triggerNode) => HTMLElement | () => document.body | 4.23.0 |
| formatter | Slider 会把当前值传给 `formatter`,并在 Tooltip 中显示 `formatter` 的返回值,若为 null,则隐藏 Tooltip | value => ReactNode \| null | IDENTITY | 4.23.0 |
## 方法
| 名称 | 描述 | 版本 |
| ------- | -------- | ---- |
| blur() | 移除焦点 | |
| focus() | 获取焦点 | |
## Semantic DOM
https://ant.design/components/slider-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Slider)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| controlSize | 滑动输入高度 | number | 10 |
| dotActiveBorderColor | 圆点激活态边框颜色 | string | #91caff |
| dotBorderColor | 圆点边框颜色 | string | #f0f0f0 |
| dotSize | 滑块圆点尺寸 | number | 8 |
| handleActiveColor | 滑块激活态边框色 | string | #1677ff |
| handleActiveOutlineColor | 滑块激活态外框色 | string | rgba(22,119,255,0.2) |
| handleColor | 滑块颜色 | string | #91caff |
| handleColorDisabled | 滑块禁用颜色 | string | #bfbfbf |
| handleLineWidth | 滑块边框宽度 | string \| number | 2 |
| handleLineWidthHover | 滑块边框宽度(悬浮态) | string \| number | 2.5 |
| handleSize | 滑块尺寸 | number | 10 |
| handleSizeHover | 滑块尺寸(悬浮态) | number | 12 |
| railBg | 轨道背景色 | string | rgba(0,0,0,0.04) |
| railHoverBg | 轨道背景色(悬浮态) | string | rgba(0,0,0,0.06) |
| railSize | 轨道高度 | number | 4 |
| trackBg | 轨道已覆盖部分背景色 | string | #91caff |
| trackBgDisabled | 轨道禁用态背景色 | string | rgba(0,0,0,0.04) |
| trackHoverBg | 轨道已覆盖部分背景色(悬浮态) | string | #69b1ff |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadiusXS | XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 | number | |
| colorBgElevated | 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 | string | |
| colorFillContentHover | 控制内容区域背景色在鼠标悬停时的样式。 | string | |
| colorPrimaryBorderHover | 主色梯度下的描边用色的悬浮态,Slider 、Button 等组件的描边 Hover 时会使用。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlHeightLG | 较高的组件高度 | number | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
---
## space-cn
Source: https://ant.design/components/space-cn.md
---
category: Components
group: 布局
title: Space
subtitle: 间距
description: 设置组件之间的间距。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*ZiJ3SbOH9SUAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*37T2R6O9oi0AAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
避免组件紧贴在一起,拉开统一的空间。
- 适合行内元素的水平间距。
- 可以设置各种水平对齐方式。
- 需要表单组件之间紧凑连接且合并边框时,使用 Space.Compact(自 `antd@4.24.0` 版本开始提供该组件)。
### 与 Flex 组件的区别 {#difference-with-flex-component}
- Space 为内联元素提供间距,其本身会为每一个子元素添加包裹元素用于内联对齐。适用于行、列中多个子元素的等距排列。
- Flex 为块级元素提供间距,其本身不会添加包裹元素。适用于垂直或水平方向上的子元素布局,并提供了更多的灵活性和控制能力。
## 代码演示 {#examples}
### 基本用法
相邻组件水平间距。
```tsx
import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Popconfirm, Space, Upload } from 'antd';
const App: React.FC = () => (
Space
Button
}>Click to Upload
Confirm
);
export default App;
```
### 垂直间距
相邻组件垂直间距。
```tsx
import React from 'react';
import { Card, Space } from 'antd';
const App: React.FC = () => (
Card content
Card content
Card content
Card content
Card content
Card content
);
export default App;
```
### 间距大小
使用 `size` 设置元素之间的间距,预设了 `small`、`middle`、`large` 三种尺寸,也可以自定义间距,若不设置 `size`,则默认为 `small`。
```tsx
import React, { useState } from 'react';
import { Button, Radio, Slider, Space } from 'antd';
import type { ConfigProviderProps } from 'antd';
type SizeType = ConfigProviderProps['componentSize'];
const App: React.FC = () => {
const [size, setSize] = useState('small');
const [customSize, setCustomSize] = React.useState(0);
return (
<>
setSize(e.target.value)}>
{['small', 'middle', 'large', 'customize'].map((item) => (
{item}
))}
{size === 'customize' && (
<>
>
)}
Primary
Default
Dashed
Link
>
);
};
export default App;
```
### 对齐
设置对齐模式。
```tsx
import React from 'react';
import { Button, Space } from 'antd';
const App: React.FC = () => (
center
Primary
Block
start
Primary
Block
end
Primary
Block
baseline
Primary
Block
);
export default App;
```
### 自动换行
自动换行。
```tsx
import React from 'react';
import { Button, Space } from 'antd';
const App: React.FC = () => (
{Array.from({ length: 20 }).map((_, index) => (
// eslint-disable-next-line react/no-array-index-key
Button
))}
);
export default App;
```
### 分隔符
相邻组件分隔符。
```tsx
import React from 'react';
import { Divider, Space, Typography } from 'antd';
const App: React.FC = () => (
}>
Link
Link
Link
);
export default App;
```
### 紧凑布局组合
使用 Space.Compact 让表单组件之间紧凑连接且合并边框。
```tsx
import React from 'react';
import { CopyOutlined } from '@ant-design/icons';
import {
AutoComplete,
Button,
Cascader,
ColorPicker,
DatePicker,
Input,
InputNumber,
Select,
Space,
TimePicker,
Tooltip,
TreeSelect,
} from 'antd';
const { TreeNode } = TreeSelect;
const App: React.FC = () => (
Submit
Submit
} />
查询
{}}
>
leaf3} />
Submit
$
$
Button
$
);
export default App;
```
### Button 紧凑布局
Button 组件紧凑排列的示例。
```tsx
import React from 'react';
import {
CommentOutlined,
DownloadOutlined,
EllipsisOutlined,
HeartOutlined,
LikeOutlined,
MailOutlined,
MobileOutlined,
ShareAltOutlined,
StarOutlined,
WarningOutlined,
} from '@ant-design/icons';
import { Button, Dropdown, Space, Tooltip } from 'antd';
const App: React.FC = () => (
} />
} />
} />
} />
} />
} />
,
},
{
key: '2',
label: 'Mail',
icon: ,
},
{
key: '3',
label: 'Mobile',
icon: ,
},
],
}}
trigger={['click']}
>
} />
Button 1
Button 2
Button 3
Button 4
} disabled />
} />
Button 1
Button 2
Button 3
} disabled />
} />
Button 4
} />
);
export default App;
```
### 垂直方向紧凑布局
垂直方向的紧凑布局,目前仅支持 Button 组合。
```tsx
import React from 'react';
import { Button, Space } from 'antd';
const App: React.FC = () => (
Button 1
Button 2
Button 3
Button 1
Button 2
Button 3
Button 1
Button 2
Button 3
Button 1
Button 2
Button 3
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Space 的[语义化结构](#semantic-dom)样式。
```tsx
import * as React from 'react';
import { Button, Space } from 'antd';
import type { SpaceProps } from 'antd';
const classNamesObject: SpaceProps['classNames'] = {
root: 'demo-space-root',
item: 'demo-space-item',
separator: 'demo-space-separator',
};
const classNamesFn: SpaceProps['classNames'] = (info) => {
if (info.props.orientation === 'vertical') {
return {
root: 'demo-space-root--vertical',
} satisfies SpaceProps['classNames'];
} else {
return {
root: 'demo-space-root--horizontal',
} satisfies SpaceProps['classNames'];
}
};
const stylesObject: SpaceProps['styles'] = {
root: { borderWidth: 2, borderStyle: 'dashed', padding: 8, marginBottom: 10 },
item: { backgroundColor: '#f0f0f0', padding: 4 },
separator: { color: 'red', fontWeight: 'bold' },
};
const stylesFn: SpaceProps['styles'] = (info) => {
if (info.props.size === 'large') {
return {
root: {
backgroundColor: '#e6f7ff',
borderColor: '#1890ff',
padding: 8,
},
} satisfies SpaceProps['styles'];
} else {
return {
root: {
backgroundColor: '#fff7e6',
borderColor: '#fa8c16',
},
} satisfies SpaceProps['styles'];
}
};
const App: React.FC = () => {
return (
Styled Button 1
Styled Button 2
Styled Button 3
Large Space Button 1
Large Space Button 2
Large Space Button 3
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Space
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| align | 对齐方式 | `start` \| `end` \|`center` \|`baseline` | - | 4.2.0 |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props: SpaceProps })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| ~~direction~~ | 间距方向 | `vertical` \| `horizontal` | `horizontal` | 4.1.0 |
| orientation | 间距方向 | `vertical` \| `horizontal` | `horizontal` | |
| size | 间距大小 | [Size](#size) \| [Size\[\]](#size) | `small` | 4.1.0 \| Array: 4.9.0 |
| ~~split~~ | 设置分隔符, 请使用 `separator` 替换 | ReactNode | - | 4.7.0 |
| separator | 设置分隔符 | ReactNode | - | - |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props: SpaceProps })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| vertical | 是否垂直,和 `orientation` 同时配置以 `orientation` 优先 | boolean | false | - |
| wrap | 是否自动换行,仅在 `horizontal` 时有效 | boolean | false | 4.9.0 |
### Size
`'small' | 'middle' | 'large' | number`
### Space.Compact
需要表单组件之间紧凑连接且合并边框时,使用 Space.Compact,支持的组件有:
- Button
- AutoComplete
- Cascader
- DatePicker
- Input/Input.Search
- InputNumber
- Select
- TimePicker
- TreeSelect
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| block | 将宽度调整为父元素宽度的选项 | boolean | false | 4.24.0 |
| ~~direction~~ | 指定排列方向 | `vertical` \| `horizontal` | `horizontal` | 4.24.0 |
| orientation | 指定排列方向 | `vertical` \| `horizontal` | `horizontal` | |
| size | 子组件大小 | `large` \| `middle` \| `small` | `middle` | 4.24.0 |
| vertical | 是否垂直,和 `orientation` 同时配置以 `orientation` 优先 | boolean | false | - |
### Space.Addon
> 自 antd@5.29.0 版本开始提供该组件。
用于在紧凑布局中创建自定义单元格。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| -------- | ---------- | --------- | ------ | ------ |
| children | 自定义内容 | ReactNode | - | 5.29.0 |
## Semantic DOM
https://ant.design/components/space-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| padding | 控制元素的内间距。 | number | |
| paddingLG | 控制元素的大内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
---
## spin-cn
Source: https://ant.design/components/spin-cn.md
---
category: Components
group: 反馈
title: Spin
subtitle: 加载中
description: 用于页面和区块的加载中状态。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*5mC5TomY4B0AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*i43_ToFrL8YAAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。
## 代码演示 {#examples}
### 基本用法
一个简单的 loading 状态。
```tsx
import React from 'react';
import { Spin } from 'antd';
const App: React.FC = () => ;
export default App;
```
### 各种大小
小的用于文本加载,默认用于卡片容器级加载,大的用于**页面级**加载。
```tsx
import React from 'react';
import { Flex, Spin } from 'antd';
const App: React.FC = () => (
);
export default App;
```
### 卡片加载中
可以直接把内容内嵌到 `Spin` 中,将现有容器变为加载状态。
```tsx
import React from 'react';
import { Alert, Flex, Spin, Switch } from 'antd';
const App: React.FC = () => {
const [loading, setLoading] = React.useState(false);
return (
Loading state:
);
};
export default App;
```
### 自定义描述文案
自定义描述文案。
```tsx
import React from 'react';
import { Alert, Flex, Spin } from 'antd';
const contentStyle: React.CSSProperties = {
padding: 50,
background: 'rgba(0, 0, 0, 0.05)',
borderRadius: 4,
};
const content =
;
const App: React.FC = () => (
{content}
{content}
{content}
);
export default App;
```
### 延迟
延迟显示 loading 效果。当 spinning 状态在 `delay` 时间内结束,则不显示 loading 状态。
```tsx
import React from 'react';
import { Alert, Flex, Spin, Switch } from 'antd';
const App: React.FC = () => {
const [loading, setLoading] = React.useState(false);
return (
Loading state:
);
};
export default App;
```
### 自定义指示符
使用自定义指示符。
```tsx
import React from 'react';
import { LoadingOutlined } from '@ant-design/icons';
import { Flex, Spin } from 'antd';
const App: React.FC = () => (
} size="small" />
} />
} size="large" />
} />
);
export default App;
```
### 进度
展示进度,当设置 `percent="auto"` 时会预估一个永远不会停止的进度条。
```tsx
import React from 'react';
import { Flex, Spin, Switch } from 'antd';
const App: React.FC = () => {
const [auto, setAuto] = React.useState(false);
const [percent, setPercent] = React.useState(-50);
const timerRef = React.useRef>(null);
React.useEffect(() => {
timerRef.current = setTimeout(() => {
setPercent((v) => {
const nextPercent = v + 5;
return nextPercent > 150 ? -50 : nextPercent;
});
}, 100);
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, [percent]);
const mergedPercent = auto ? 'auto' : percent;
return (
{
setAuto(!auto);
setPercent(-50);
}}
/>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Spin 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Spin } from 'antd';
import type { SpinProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
padding: 8px;
`,
}));
const stylesObject: SpinProps['styles'] = {
indicator: {
color: '#00d4ff',
},
};
const stylesFn: SpinProps['styles'] = ({ props }) => {
if (props.size === 'small') {
return {
indicator: {
color: '#722ed1',
},
} satisfies SpinProps['styles'];
}
return {};
};
const App: React.FC = () => {
const sharedProps: SpinProps = {
spinning: true,
percent: 0,
classNames: { root: classNames.root },
};
return (
);
};
export default App;
```
### 全屏
`fullscreen` 属性非常适合创建流畅的页面加载器。它添加了半透明覆盖层,并在其中心放置了一个旋转加载符号。
```tsx
import React from 'react';
import { Button, Spin } from 'antd';
const App: React.FC = () => {
const [spinning, setSpinning] = React.useState(false);
const [percent, setPercent] = React.useState(0);
const showLoader = () => {
setSpinning(true);
let ptg = -10;
const interval = setInterval(() => {
ptg += 5;
setPercent(ptg);
if (ptg > 120) {
clearInterval(interval);
setSpinning(false);
setPercent(0);
}
}, 100);
};
return (
<>
Show fullscreen
>
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| delay | 延迟显示加载效果的时间(防止闪烁) | number (毫秒) | - | |
| description | 可以自定义描述文案 | ReactNode | - | 6.3.0 |
| fullscreen | 显示带有 `Spin` 组件的背景 | boolean | false | 5.11.0 |
| indicator | 加载指示符 | ReactNode | - | |
| percent | 展示进度,当设置 `percent="auto"` 时会预估一个永远不会停止的进度 | number \| 'auto' | - | 5.18.0 |
| size | 组件大小,可选值为 `small` `default` `large` | string | `default` | |
| spinning | 是否为加载中状态 | boolean | true | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| ~~tip~~ | 当作为包裹元素时,可以自定义描述文案。已废弃,请使用 `description` | ReactNode | - | |
| ~~wrapperClassName~~ | 包装器的类属性。已废弃,请使用 `classNames.root` | string | - | |
### 静态方法
- `Spin.setDefaultIndicator(indicator: ReactNode)`
你可以自定义全局默认 Spin 的元素。
## Semantic DOM
https://ant.design/components/spin-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Spin)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| contentHeight | 内容区域高度 | string \| number | 400 |
| dotSize | 加载图标尺寸 | number | 20 |
| dotSizeLG | 大号加载图标尺寸 | number | 32 |
| dotSizeSM | 小号加载图标尺寸 | number | 14 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorBgMask | 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer、Image 等组件的蒙层使用的是该 token | string | |
| colorFillSecondary | 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorWhite | 不随主题变化的纯白色 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| paddingSM | 控制元素的小内间距。 | number | |
| zIndexPopupBase | 浮层类组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 FloatButton、 Affix、Modal 等 | number | |
---
## splitter-cn
Source: https://ant.design/components/splitter-cn.md
---
category: Components
group: 布局
title: Splitter
subtitle: 分隔面板
description: 自由切分指定区域
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*f0SISaETY0wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*y92yRYhObU8AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 1
---
## 何时使用 {#when-to-use}
- 可以水平或垂直地分隔区域。
- 当需要自由拖拽调整各区域大小。
- 当需要指定区域的最大最小宽高时。
## 代码演示 {#examples}
### 基本用法
初始化面板大小,面板大小限制。
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
export const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### 受控模式
受控调整尺寸。当 Panel 之间任意一方禁用 `resizable`,则其拖拽将被禁用。
```tsx
import React from 'react';
import { Button, Flex, Splitter, Switch, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => {
const [sizes, setSizes] = React.useState<(number | string)[]>(['50%', '50%']);
const [enabled, setEnabled] = React.useState(true);
return (
setEnabled(!enabled)}
checkedChildren="Enabled"
unCheckedChildren="Disabled"
/>
setSizes(['50%', '50%'])}>Reset
);
};
export default App;
```
### 垂直方向
使用垂直布局。
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### 可折叠
配置 `collapsible` 提供快捷收缩能力。可以通过 `min` 限制收缩后不能通过拖拽展开。
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
import type { SplitterProps } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const CustomSplitter: React.FC> = ({ style, ...restProps }) => (
);
const App: React.FC = () => (
);
export default App;
```
### 可折叠图标显示
配置 `collapsible.showCollapsibleIcon` 控制可折叠图标的显示方式。
```tsx
import React, { useState } from 'react';
import { Flex, Radio, Splitter, Typography } from 'antd';
import type { RadioChangeEvent } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
const Desc: React.FC> = (props) => (
{props.text}
);
const options: CheckboxGroupProps<'auto' | boolean>['options'] = [
{ label: 'Auto', value: 'auto' },
{ label: 'True', value: true },
{ label: 'False', value: false },
];
const App: React.FC = () => {
const [showIconMode, setShowIconMode] = useState<'auto' | boolean>(true);
const onChange = (e: RadioChangeEvent) => {
setShowIconMode(e.target.value);
};
return (
ShowCollapsibleIcon:
);
};
export default App;
```
### 多面板
多面板
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
Panel {props.text}
);
const App: React.FC = () => (
);
export default App;
```
### 复杂组合
复杂组合面板,快捷折叠,禁止改变大小
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### 延迟渲染模式
延迟渲染模式,拖拽时不会立即更新大小,而是等到松手时才更新。
```tsx
import React from 'react';
import { Flex, Space, Splitter, Typography } from 'antd';
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => (
);
export default App;
```
### 自定义样式
自定义操作元素样式
```tsx
import React from 'react';
import {
CaretDownOutlined,
CaretLeftOutlined,
CaretRightOutlined,
CaretUpOutlined,
ColumnWidthOutlined,
} from '@ant-design/icons';
import { ConfigProvider, Divider, Flex, Splitter, Typography } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
dragger: {
'&::before': {
backgroundColor: 'transparent !important',
border: `1px dashed ${token.controlItemBgHover}`,
},
'&:hover::before': {
border: `1px dashed ${token.colorPrimary}`,
},
},
draggerActive: {
'&::before': {
border: `1px dashed ${token.colorPrimary}`,
},
},
draggerIcon: {
'&:hover': {
color: token.colorPrimary,
},
},
collapsibleIcon: {
fontSize: 16,
color: token.colorTextDescription,
'&:hover': {
color: token.colorPrimary,
},
},
}));
const Desc: React.FC> = (props) => (
{props.text}
);
const App: React.FC = () => {
const { styles } = useStyles();
return (
}
collapsibleIcon={{
start: ,
end: ,
}}
>
,
end: ,
}}
>
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Splitter 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Splitter, Typography } from 'antd';
import type { SplitterProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const Desc: React.FC> = (
props,
) => {
return (
{props.text}
);
};
const styles = createStaticStyles(({ css, cssVar }) => ({
boxShadow: css`
box-shadow: ${cssVar.boxShadowSecondary};
`,
}));
const stylesObject: SplitterProps['styles'] = {
root: { backgroundColor: '#fffbe6' },
dragger: { backgroundColor: 'rgba(194,223,252,0.4)' },
};
const stylesFn: SplitterProps['styles'] = ({ props }) => {
if (props.orientation === 'horizontal') {
return {
root: {
borderWidth: 2,
borderStyle: 'dashed',
marginBottom: 10,
},
} satisfies SplitterProps['styles'];
}
return {};
};
const App: React.FC = () => {
const splitSharedProps: SplitterProps = {
style: { height: 200 },
classNames: { root: styles.boxShadow },
};
return (
);
};
export default App;
```
### 双击重置
双击拖拽条 Splitter.Panel 重置为默认大小。
```tsx
import React, { useState } from 'react';
import { Flex, Splitter, Typography } from 'antd';
const defaultSizes = ['30%', '40%', '30%'];
const Desc: React.FC> = (props) => (
Panel {props.text}
);
const App: React.FC = () => {
const [sizes, setSizes] = useState<(number | string)[]>(defaultSizes);
const handleDoubleClick = () => {
setSizes(defaultSizes);
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
> Splitter 组件需要通过子元素计算面板大小,因而其子元素仅支持 `Splitter.Panel`。
### Splitter
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| collapsibleIcon | 折叠图标 | `{start?: ReactNode; end?: ReactNode}` | - | 6.0.0 |
| draggerIcon | 拖拽图标 | `ReactNode` | - | 6.0.0 |
| ~~layout~~ | 布局方向 | `horizontal` \| `vertical` | `horizontal` | - |
| lazy | 延迟渲染模式 | `boolean` | `false` | 5.23.0 |
| onCollapse | 展开-收起时回调 | `(collapsed: boolean[], sizes: number[]) => void` | - | 5.28.0 |
| orientation | 布局方向 | `horizontal` \| `vertical` | `horizontal` | - |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| vertical | 排列方向,与 `orientation` 同时存在,以 `orientation` 优先 | boolean | `false` | |
| onDraggerDoubleClick | 双击拖拽条回调 | `(index: number) => void` | - | 6.3.0 |
| onResize | 面板大小变化回调 | `(sizes: number[]) => void` | - | - |
| onResizeEnd | 拖拽结束回调 | `(sizes: number[]) => void` | - | - |
| onResizeStart | 开始拖拽之前回调 | `(sizes: number[]) => void` | - | - |
### Panel
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| collapsible | 快速折叠 | `boolean \| { start?: boolean; end?: boolean; showCollapsibleIcon?: boolean \| 'auto' }` | `false` | showCollapsibleIcon: 5.27.0 |
| defaultSize | 初始面板大小,支持数字 px 或者文字 '百分比%' 类型 | `number \| string` | - | - |
| max | 最大阈值,支持数字 px 或者文字 '百分比%' 类型 | `number \| string` | - | - |
| min | 最小阈值,支持数字 px 或者文字 '百分比%' 类型 | `number \| string` | - | - |
| resizable | 是否开启拖拽伸缩 | `boolean` | `true` | - |
| size | 受控面板大小,支持数字 px 或者文字 '百分比%' 类型 | `number \| string` | - | - |
## Semantic DOM
https://ant.design/components/splitter-cn/semantic.md
## 主题变量(Design Token){#design-token}
---
## statistic-cn
Source: https://ant.design/components/statistic-cn.md
---
category: Components
group: 数据展示
title: Statistic
subtitle: 统计数值
description: 展示统计数值。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*YL7PRYNtH-4AAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*BPWDRbSYxJ4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 当需要突出某个或某组数字时。
- 当需要展示带描述的统计类数据时使用。
## 代码演示 {#examples}
### 基本
简单的展示。
```tsx
import React from 'react';
import { Button, Col, Row, Statistic } from 'antd';
const App: React.FC = () => (
Recharge
);
export default App;
```
### 单位
通过前缀和后缀添加单位。
```tsx
import React from 'react';
import { LikeOutlined } from '@ant-design/icons';
import { Col, Row, Statistic } from 'antd';
const App: React.FC = () => (
} />
);
export default App;
```
### 动画效果
给数值添加动画进入效果,需要配合 [react-countup](https://www.npmjs.com/package/react-countup)。
```tsx
import React from 'react';
import type { StatisticProps } from 'antd';
import { Col, Row, Statistic } from 'antd';
import CountUp from 'react-countup';
const formatter: StatisticProps['formatter'] = (value) => (
);
const App: React.FC = () => (
);
export default App;
```
### 在卡片中使用
在卡片中展示统计数值。
```tsx
import React from 'react';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import { Card, Col, Row, Statistic } from 'antd';
const App: React.FC = () => (
}
suffix="%"
/>
}
suffix="%"
/>
);
export default App;
```
### 计时器
计时器组件。
```tsx
import React from 'react';
import type { StatisticTimerProps } from 'antd';
import { Col, Row, Statistic } from 'antd';
const { Timer } = Statistic;
const deadline = Date.now() + 1000 * 60 * 60 * 24 * 2 + 1000 * 30; // Dayjs is also OK
const before = Date.now() - 1000 * 60 * 60 * 24 * 2 + 1000 * 30;
const tenSecondsLater = Date.now() + 10 * 1000;
const onFinish: StatisticTimerProps['onFinish'] = () => {
console.log('finished!');
};
const onChange: StatisticTimerProps['onChange'] = (val) => {
if (typeof val === 'number' && 4.95 * 1000 < val && val < 5 * 1000) {
console.log('changed!');
}
};
const App: React.FC = () => (
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Statistic 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { ArrowUpOutlined } from '@ant-design/icons';
import { Flex, Statistic } from 'antd';
import type { StatisticProps } from 'antd';
import { createStaticStyles } from 'antd-style';
const classNames = createStaticStyles(({ css }) => ({
root: css`
border: 2px dashed #ccc;
padding: 16px;
border-radius: 8px;
`,
}));
const styleFn: StatisticProps['styles'] = ({ props }) => {
const numValue = Number(props.value ?? 0);
const isNegative = Number.isFinite(numValue) && numValue < 0;
if (isNegative) {
return {
title: {
color: '#ff4d4f',
},
content: {
color: '#ff7875',
},
} satisfies StatisticProps['styles'];
}
return {};
};
const App: React.FC = () => {
const statisticSharedProps: StatisticProps = {
classNames: { root: classNames.root },
prefix: ,
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
#### Statistic
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义 Statistic 组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom), string> | - | |
| decimalSeparator | 设置小数点 | string | `.` | |
| formatter | 自定义数值展示 | (value) => ReactNode | - | |
| groupSeparator | 设置千分位标识符 | string | `,` | |
| loading | 数值是否加载中 | boolean | false | 4.8.0 |
| precision | 数值精度 | number | - | |
| prefix | 设置数值的前缀 | ReactNode | - | |
| styles | 用于自定义 Statistic 组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom) , CSSProperties> \| (info: { props }) => Record<[SemanticDOM](#semantic-dom) , CSSProperties> | - | |
| suffix | 设置数值的后缀 | ReactNode | - | |
| title | 数值的标题 | ReactNode | - | |
| value | 数值内容 | string \| number | - | |
| valueStyle | 设置数值区域的样式 | CSSProperties | - | |
#### Statistic.Countdown Deprecated
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| format | 格式化倒计时展示,参考 [dayjs](https://day.js.org/) | string | `HH:mm:ss` | |
| prefix | 设置数值的前缀 | ReactNode | - | |
| suffix | 设置数值的后缀 | ReactNode | - | |
| title | 数值的标题 | ReactNode | - | |
| value | 数值内容 | number | - | |
| valueStyle | 设置数值区域的样式 | CSSProperties | - | |
| onFinish | 倒计时完成时触发 | () => void | - | |
| onChange | 倒计时时间变化时触发 | (value: number) => void | - | |
#### Statistic.Timer 5.25.0+
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| type | 计时类型,正计时或者倒计时 | `countdown` `countup` | - | |
| format | 格式化倒计时展示,参考 [dayjs](https://day.js.org/) | string | `HH:mm:ss` | |
| prefix | 设置数值的前缀 | ReactNode | - | |
| suffix | 设置数值的后缀 | ReactNode | - | |
| title | 数值的标题 | ReactNode | - | |
| value | 数值内容 | number | - | |
| valueStyle | 设置数值区域的样式 | CSSProperties | - | |
| onFinish | 倒计时完成时触发, 指定为 `countup` 此属性不生效 | () => void | - | |
| onChange | 倒计时时间变化时触发 | (value: number) => void | - | |
## Semantic DOM
https://ant.design/components/statistic-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Statistic)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| contentFontSize | 内容字体大小 | number | 24 |
| titleFontSize | 标题字体大小 | number | 14 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextHeading | 控制标题字体颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| lineHeight | 文本行高 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| padding | 控制元素的内间距。 | number | |
---
## steps-cn
Source: https://ant.design/components/steps-cn.md
---
category: Components
group: 导航
title: Steps
subtitle: 步骤条
description: 引导用户按照流程完成任务的导航条。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*677sTqCpE3wAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*cFsBQLA0b7UAAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
当任务复杂或者存在先后关系时,将其分解成一系列步骤,从而简化任务。
## 代码演示 {#examples}
### 基本用法
简单的步骤条,使用 `variant` 属性来设置不同的样式,使用 `size` 控制大小。
```tsx
import React from 'react';
import { Flex, Steps } from 'antd';
const content = 'This is a content.';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Progress',
content,
subTitle: 'Left 00:00:08',
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => (
);
export default App;
```
### 步骤运行错误
使用 Steps 的 `status` 属性来指定当前步骤的状态。
```tsx
import React from 'react';
import { Steps } from 'antd';
const content = 'This is a content';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Process',
content,
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => ;
export default App;
```
### 竖直方向的步骤条
简单的竖直方向的步骤条。
```tsx
import React from 'react';
import { Flex, Steps } from 'antd';
const content = 'This is a content.';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Progress',
content,
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => (
);
export default App;
```
### 可点击
设置 `onChange` 后,Steps 变为可点击状态。
```tsx
import React, { useState } from 'react';
import { Divider, Steps } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(0);
const onChange = (value: number) => {
console.log('onChange:', value);
setCurrent(value);
};
const content = 'This is a content.';
return (
<>
>
);
};
export default App;
```
### 面板式步骤
面板类型的步骤条。
```tsx
import React, { useState } from 'react';
import { Flex, Steps } from 'antd';
import type { StepsProps } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(0);
const onChange = (value: number) => {
console.log('onChange:', value);
setCurrent(value);
};
const sharedProps: StepsProps = {
type: 'panel',
current,
onChange,
items: [
{
title: 'Step 1',
subTitle: '00:00',
content: 'This is a content.',
},
{
title: 'Step 2',
content: 'This is a content.',
status: 'error',
},
{
title: 'Step 3',
content: 'This is a content.',
},
],
};
return (
);
};
export default App;
```
### 带图标的步骤条
通过设置 `items` 的 `icon` 属性,可以启用自定义图标。
```tsx
import React from 'react';
import { LoadingOutlined, SmileOutlined, SolutionOutlined, UserOutlined } from '@ant-design/icons';
import { Steps } from 'antd';
const App: React.FC = () => (
,
},
{
title: 'Verification',
status: 'finish',
icon: ,
},
{
title: 'Pay',
status: 'process',
icon: ,
},
{
title: 'Done',
status: 'wait',
icon: ,
},
]}
/>
);
export default App;
```
### 标签放置位置与进度
使用 `titlePlacement` 设置标签位置,通过 `percent` 显示进度。
```tsx
import React from 'react';
import { Steps } from 'antd';
const content = 'This is a content.';
const items = [
{
title: 'Finished',
content,
},
{
title: 'In Progress',
content,
},
{
title: 'Waiting',
content,
},
];
const App: React.FC = () => (
<>
>
);
export default App;
```
### 点状步骤条
包含步骤点的进度条。
```tsx
import React from 'react';
import { Divider, Flex, Steps } from 'antd';
import type { StepsProps } from 'antd';
const items = [
{
title: 'Finished',
content: 'This is a content.',
},
{
title: 'In Progress',
content: 'This is a content.',
},
{
title: 'Waiting',
content: 'This is a content.',
},
];
const sharedProps: StepsProps = {
type: 'dot',
current: 1,
items,
};
const sharedVerticalProps = {
...sharedProps,
orientation: 'vertical',
style: {
flex: 'auto',
},
} as const;
const App: React.FC = () => (
);
export default App;
```
### 导航步骤
导航类型的步骤条。
```tsx
import React, { useState } from 'react';
import { Flex, Steps } from 'antd';
const App: React.FC = () => {
const [current, setCurrent] = useState(0);
const onChange = (value: number) => {
console.log('onChange:', value);
setCurrent(value);
};
return (
);
};
export default App;
```
### 内联步骤
内联类型的步骤条,适用于列表内容场景中展示对象所在流程、当前状态的情况。
```tsx
import React from 'react';
import type { StepsProps } from 'antd';
import { Avatar, List, Steps } from 'antd';
const data = [
{
title: 'Ant Design Title 1',
current: 0,
},
{
title: 'Ant Design Title 2',
current: 1,
status: 'error',
},
{
title: 'Ant Design Title 3',
current: 2,
},
{
title: 'Ant Design Title 4',
current: 1,
},
];
const items = [
{
title: 'Step 1',
content: 'This is Step 1',
},
{
title: 'Step 2',
content: 'This is Step 2',
},
{
title: 'Step 3',
content: 'This is Step 3',
},
];
const App: React.FC = () => (
(
}
title={{item.title} }
description="Ant Design, a design language for background applications, is refined by Ant UED Team"
/>
)}
/>
);
export default App;
```
### 内联样式组合
内联步骤条修改样式,通过 `offset` 进行对齐。
```tsx
import React from 'react';
import type { StepsProps } from 'antd';
import { Flex, Steps, theme } from 'antd';
const items: StepsProps['items'] = Array.from({ length: 5 }, (_, index) => ({
title: `Step ${index + 1}`,
subTitle: 'Sub Title',
content: `This is Step ${index + 1}`,
}));
const App: React.FC = () => {
const { token } = theme.useToken();
return (
);
};
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Steps 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Steps } from 'antd';
import type { StepsProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyles = createStyles(({ token }) => ({
root: {
border: `2px dashed ${token.colorBorder}`,
borderRadius: token.borderRadius,
padding: token.padding,
},
}));
const stylesObject: StepsProps['styles'] = {
itemIcon: { borderRadius: '30%' },
itemContent: { fontStyle: 'italic' },
};
const stylesFn: StepsProps['styles'] = (info) => {
if (info.props.type === 'navigation') {
return {
root: {
borderColor: '#1890ff',
},
} satisfies StepsProps['styles'];
}
return {};
};
const App: React.FC = () => {
const { styles } = useStyles();
const sharedProps: StepsProps = {
items: [
{ title: 'Finished', content: 'This is a content.' },
{ title: 'In Progress', content: 'This is a content.' },
{ title: 'Waiting', content: 'This is a content.' },
],
current: 1,
classNames: { root: styles.root },
};
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
### Steps
整体步骤条。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - | |
| current | 指定当前步骤,从 0 开始记数。在子 Step 元素中,可以通过 `status` 属性覆盖状态 | number | 0 | |
| ~~direction~~ | 指定步骤条方向。目前支持水平(`horizontal`)和竖直(`vertical`)两种方向 | string | `horizontal` | |
| iconRender | 自定义渲染图标,请优先使用 `items.icon` | (oriNode, info: { index, active, item }) => ReactNode | - | |
| initial | 起始序号,从 0 开始记数 | number | 0 | |
| ~~labelPlacement~~ | 指定标签放置位置,默认水平放图标右侧,可选 `vertical` 放图标下方 | string | `horizontal` | |
| orientation | 指定步骤条方向。目前支持水平(`horizontal`)和竖直(`vertical`)两种方向 | string | `horizontal` | |
| percent | 当前 `process` 步骤显示的进度条进度(只对基本类型的 Steps 生效) | number | - | 4.5.0 |
| progressDot | 点状步骤条,可以设置为一个 function,`titlePlacement` 将强制为 `vertical` | boolean \| (iconDot, { index, status, title, content }) => ReactNode | false | |
| responsive | 当屏幕宽度小于 `532px` 时自动变为垂直模式 | boolean | true | |
| size | 指定大小,目前支持普通(`default`)和迷你(`small`) | string | `default` | |
| status | 指定当前步骤的状态,可选 `wait` `process` `finish` `error` | string | `process` | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - | |
| titlePlacement | 指定标签放置位置,默认水平放图标右侧,可选 `vertical` 放图标下方 | string | `horizontal` | |
| type | 步骤条类型,可选 `default` `dot` `inline` `navigation` `panel` | string | `default` | |
| variant | 设置样式变体 | `filled` \| `outlined` | `filled` | |
| onChange | 点击切换步骤时触发 | (current) => void | - | |
| items | 配置选项卡内容 | [StepItem](#stepitem) | [] | 4.24.0 |
### StepItem
步骤条内的每一个步骤。
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| content | 步骤的详情描述,可选 | ReactNode | - | |
| ~~description~~ | 步骤的详情描述,可选 | ReactNode | - | |
| disabled | 禁用点击 | boolean | false | |
| icon | 步骤图标的类型,可选 | ReactNode | - | |
| status | 指定状态。当不配置该属性时,会使用 Steps 的 `current` 来自动指定状态。可选:`wait` `process` `finish` `error` | string | `wait` | |
| subTitle | 子标题 | ReactNode | - | |
| title | 标题 | ReactNode | - | |
## Semantic DOM
### Steps
https://ant.design/components/steps-cn/semantic.md
### StepItem
https://ant.design/components/steps-cn/semantic_items.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Steps)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| customIconFontSize | 自定义图标大小 | number | 24 |
| customIconSize | 自定义图标容器尺寸 | number | 32 |
| customIconTop | 自定义图标 top | number | 0 |
| dotCurrentSize | 点状步骤点当前大小 | number | 10 |
| dotSize | 点状步骤点大小 | number | 8 |
| iconFontSize | 图标大小 | number | 14 |
| iconSize | 图标容器尺寸 | number | 32 |
| iconSizeSM | 小号步骤条图标大小 | number | 24 |
| iconTop | 图标 top | number | -0.5 |
| navArrowColor | 可跳转步骤条箭头颜色 | string | rgba(0,0,0,0.25) |
| navContentMaxWidth | 可跳转步骤条内容最大宽度 | MaxWidth \| undefined | unset |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| borderRadius | 基础组件的圆角大小,例如按钮、输入框、卡片等 | number | |
| borderRadiusSM | SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 | number | |
| colorBgContainer | 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 | string | |
| colorError | 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 | string | |
| colorErrorBg | 错误色的浅色背景颜色 | string | |
| colorErrorBgFilledHover | 错误色的浅色填充背景色悬浮态,目前只用在危险填充按钮的 hover 效果。 | string | |
| colorErrorHover | 错误色的深色悬浮态 | string | |
| colorFillTertiary | 三级填充色用于勾勒出元素形体的场景,如 Slider、Segmented 等。如无强调需求的情况下,建议使用三级填色作为默认填色。 | string | |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBg | 主色浅色背景颜色,一般用于视觉层级较弱的选中状态。 | string | |
| colorPrimaryBgHover | 与主色浅色背景颜色相对应的悬浮态颜色。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorSplit | 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextDescription | 控制文本描述字体颜色。 | string | |
| colorTextDisabled | 控制禁用状态下的字体颜色。 | string | |
| colorTextLabel | 控制文本标签字体颜色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextQuaternary | 第四级文本色是最浅的文本色,例如表单的输入提示文本、禁用色文本等。 | string | |
| colorTextSecondary | 作为第二梯度的文本色,一般用在不那么需要强化文本颜色的场景,例如 Label 文本、Menu 的文本选中态等场景。 | string | |
| controlHeight | Ant Design 中按钮和输入框等基础控件的高度 | number | |
| controlItemBgHover | 控制组件项在鼠标悬浮时的背景颜色。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeLG | 大号字体大小 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineHeightLG | 大型文本行高 | number | |
| lineHeightSM | 小型文本行高 | number | |
| lineType | 用于控制组件边框、分割线等的样式,默认是实线 | string | |
| lineWidth | 用于控制组件边框、分割线等的宽度 | number | |
| lineWidthBold | 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 | number | |
| margin | 控制元素外边距,中等尺寸。 | number | |
| marginSM | 控制元素外边距,中小尺寸。 | number | |
| marginXS | 控制元素外边距,小尺寸。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| motionDurationSlow | 动效播放速度,慢速。用于大型元素如面板动画交互 | string | |
| paddingSM | 控制元素的小内间距。 | number | |
| paddingXS | 控制元素的特小内间距。 | number | |
| paddingXXS | 控制元素的极小内间距。 | number | |
---
## switch-cn
Source: https://ant.design/components/switch-cn.md
---
category: Components
group: 数据录入
title: Switch
subtitle: 开关
description: 使用开关切换两种状态之间。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*rtArRpBNDZcAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*al07RK8SGf4AAAAAAAAAAAAADrJ8AQ/original
demo:
cols: 2
---
## 何时使用 {#when-to-use}
- 需要表示开关状态/两种状态之间的切换时;
- 和 `checkbox` 的区别是,切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。
## 代码演示 {#examples}
### 基本
最简单的用法。
```tsx
import React from 'react';
import { Switch } from 'antd';
const onChange = (checked: boolean) => {
console.log(`switch to ${checked}`);
};
const App: React.FC = () => ;
export default App;
```
### 不可用
Switch 失效状态。
```tsx
import React, { useState } from 'react';
import { Button, Space, Switch } from 'antd';
const App: React.FC = () => {
const [disabled, setDisabled] = useState(true);
const toggle = () => {
setDisabled(!disabled);
};
return (
Toggle disabled
);
};
export default App;
```
### 文字和图标
带有文字和图标。
```tsx
import React from 'react';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Space, Switch } from 'antd';
const App: React.FC = () => (
}
unCheckedChildren={ }
defaultChecked
/>
);
export default App;
```
### 两种大小
`size="small"` 表示小号开关。
```tsx
import React from 'react';
import { Switch } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 加载中
标识开关操作仍在执行中。
```tsx
import React from 'react';
import { Switch } from 'antd';
const App: React.FC = () => (
<>
>
);
export default App;
```
### 自定义语义结构的样式和类
通过 `classNames` 和 `styles` 传入对象/函数可以自定义 Switch 的[语义化结构](#semantic-dom)样式。
```tsx
import React from 'react';
import { Flex, Switch } from 'antd';
import type { SwitchProps } from 'antd';
import { createStyles } from 'antd-style';
const useStyle = createStyles(({ token }) => ({
root: {
width: 40,
backgroundColor: token.colorPrimary,
},
}));
const stylesObject: SwitchProps['styles'] = {
root: {
backgroundColor: '#F5D2D2',
},
};
const stylesFn: SwitchProps['styles'] = (info) => {
if (info.props.size === 'default') {
return {
root: {
backgroundColor: '#BDE3C3',
},
} satisfies SwitchProps['styles'];
}
return {};
};
const App: React.FC = () => {
const { styles: classNames } = useStyle();
return (
);
};
export default App;
```
## API
通用属性参考:[通用属性](/docs/react/common-props)
| 参数 | 说明 | 类型 | 默认值 | 版本 |
| --- | --- | --- | --- | --- |
| checked | 指定当前是否选中 | boolean | false | |
| checkedChildren | 选中时的内容 | ReactNode | - | |
| className | Switch 器类名 | string | - | |
| classNames | 用于自定义组件内部各语义化结构的 class,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), string> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), string> | - |
| defaultChecked | 初始是否选中 | boolean | false | |
| defaultValue | `defaultChecked` 的别名 | boolean | - | 5.12.0 |
| disabled | 是否禁用 | boolean | false | |
| loading | 加载中的开关 | boolean | false | |
| size | 开关大小,可选值:`default` `small` | string | `default` | |
| styles | 用于自定义组件内部各语义化结构的行内 style,支持对象或函数 | Record<[SemanticDOM](#semantic-dom), CSSProperties> \| (info: { props })=> Record<[SemanticDOM](#semantic-dom), CSSProperties> | - |
| unCheckedChildren | 非选中时的内容 | ReactNode | - | |
| value | `checked` 的别名 | boolean | - | 5.12.0 |
| onChange | 变化时的回调函数 | function(checked: boolean, event: Event) | - | |
| onClick | 点击时的回调函数 | function(checked: boolean, event: Event) | - | |
## 方法
| 名称 | 描述 |
| ------- | -------- |
| blur() | 移除焦点 |
| focus() | 获取焦点 |
## Semantic DOM
https://ant.design/components/switch-cn/semantic.md
## 主题变量(Design Token){#design-token}
## 组件 Token (Switch)
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| handleBg | 开关把手背景色 | string | #fff |
| handleShadow | 开关把手阴影 | string | 0 2px 4px 0 rgba(0,35,11,0.2) |
| handleSize | 开关把手大小 | number | 18 |
| handleSizeSM | 小号开关把手大小 | number | 12 |
| innerMaxMargin | 内容区域最大边距 | number | 24 |
| innerMaxMarginSM | 小号开关内容区域最大边距 | number | 18 |
| innerMinMargin | 内容区域最小边距 | number | 9 |
| innerMinMarginSM | 小号开关内容区域最小边距 | number | 6 |
| trackHeight | 开关高度 | string \| number | 22 |
| trackHeightSM | 小号开关高度 | string \| number | 16 |
| trackMinWidth | 开关最小宽度 | string \| number | 44 |
| trackMinWidthSM | 小号开关最小宽度 | string \| number | 28 |
| trackPadding | 开关内边距 | number | 2 |
## 全局 Token
| Token 名称 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| colorPrimary | 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 | string | |
| colorPrimaryBorder | 主色梯度下的描边用色,用在 Slider 等组件的描边上。 | string | |
| colorPrimaryHover | 主色梯度下的悬浮态。 | string | |
| colorText | 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 | string | |
| colorTextLightSolid | 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 | string | |
| colorTextQuaternary | 第四级文本色是最浅的文本色,例如表单的输入提示文本、禁用色文本等。 | string | |
| colorTextTertiary | 第三级文本色一般用于描述性文本,例如表单的中的补充说明文本、列表的描述性文本等场景。 | string | |
| fontFamily | Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 | string | |
| fontSize | 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 | number | |
| fontSizeIcon | 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 | number | |
| fontSizeSM | 小号字体大小 | number | |
| lineHeight | 文本行高 | number | |
| lineWidthFocus | 控制线条的宽度,当组件处于聚焦态时。 | number | |
| marginXXS | 控制元素外边距,最小尺寸。 | number | |
| motionDurationMid | 动效播放速度,中速。用于中型元素动画交互 | string | |
| opacityLoading | 控制加载状态的透明度。 | number | |
## FAQ
### 为什么在 Form.Item 下不能绑定数据? {#faq-binding-data}
Form.Item 默认绑定值属性到 `value` 上,而 Switch 的值属性为 `checked`。你可以通过 `valuePropName` 来修改绑定的值属性。
```tsx | pure
```
---
## table-cn
Source: https://ant.design/components/table-cn.md
---
category: Components
group: 数据展示
title: Table
subtitle: 表格
description: 展示行列数据。
cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*3yz3QqMlShYAAAAAAAAAAAAADrJ8AQ/original
coverDark: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*Sv8XQ50NB40AAAAAAAAAAAAADrJ8AQ/original
---
## 何时使用 {#when-to-use}
- 当有大量结构化的数据需要展现时;
- 当需要对数据进行排序、搜索、分页、自定义操作等复杂行为时。
## 如何使用 {#how-to-use}
指定表格的数据源 `dataSource` 为一个数组。
```jsx
const dataSource = [
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号',
},
];
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
},
{
title: '住址',
dataIndex: 'address',
key: 'address',
},
];
;
```
## 相关推荐 {#promotion}
- [Kitchen Sketch 插件 💎](https://kitchen.alipay.com/):设计师神器,两步自动生成 Ant Design 表格组件。
- [ProTable](https://procomponents.ant.design/components/table) 高级表格:在 `antd` Table 之上扩展了更多便捷易用的功能,内置搜索、筛选、刷新等常用表格行为,并为多种类型数据展示提供了内置格式化。
- [S2](https://s2.antv.vision/zh) 多维交叉分析表格:[AntV S2 和 Antd Table 有什么区别?](https://zhuanlan.zhihu.com/p/494995642)
## 代码演示 {#examples}
### 基本用法
简单的表格,最后一列是各种操作。
```tsx
import React from 'react';
import { Flex, Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
interface DataType {
key: string;
name: string;
age: number;
address: string;
tags: string[];
}
const columns: TableProps['columns'] = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (text) => {text} ,
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: (_, { tags }) => (
{tags.map((tag) => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return (
{tag.toUpperCase()}
);
})}
),
},
{
title: 'Action',
key: 'action',
render: (_, record) => (
Invite {record.name}
Delete
),
},
];
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['loser'],
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
];
const App: React.FC = () => columns={columns} dataSource={data} />;
export default App;
```
### JSX 风格的 API
使用 JSX 风格的 API(2.5.0 以后引入)
> 这个只是一个描述 `columns` 的语法糖,所以你不能用其他组件去包裹 `Column` 和 `ColumnGroup`。
```tsx
import React from 'react';
import { Flex, Space, Table, Tag } from 'antd';
const { Column, ColumnGroup } = Table;
interface DataType {
key: React.Key;
firstName: string;
lastName: string;
age: number;
address: string;
tags: string[];
}
const data: DataType[] = [
{
key: '1',
firstName: 'John',
lastName: 'Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
firstName: 'Jim',
lastName: 'Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['loser'],
},
{
key: '3',
firstName: 'Joe',
lastName: 'Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
];
const App: React.FC = () => (
dataSource={data}>
(
{tags.map((tag) => {
let color = tag.length > 5 ? 'geekblue' : 'green';
if (tag === 'loser') {
color = 'volcano';
}
return (
{tag.toUpperCase()}
);
})}
)}
/>
(
Invite {record.lastName}
Delete
)}
/>
);
export default App;
```
### 可选择
第一列是联动的选择框。可以通过 `rowSelection.type` 属性指定选择类型,默认为 `checkbox`。
> 默认点击 checkbox 触发选择行为,需要点击行触发可以参考例子:
```tsx
import React, { useState } from 'react';
import { Divider, Radio, Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
render: (text: string) => {text} ,
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
];
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
},
{
key: '4',
name: 'Disabled User',
age: 99,
address: 'Sydney No. 1 Lake Park',
},
];
// rowSelection object indicates the need for row selection
const rowSelection: TableProps['rowSelection'] = {
onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
},
getCheckboxProps: (record: DataType) => ({
disabled: record.name === 'Disabled User', // Column configuration not to be checked
name: record.name,
}),
};
const App: React.FC = () => {
const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
return (
setSelectionType(e.target.value)} value={selectionType}>
Checkbox
radio
rowSelection={{ type: selectionType, ...rowSelection }}
columns={columns}
dataSource={data}
/>
);
};
export default App;
```
### 选择和操作
选择后进行操作,完成后清空选择,通过 `rowSelection.selectedRowKeys` 来控制选中项。
```tsx
import React, { useState } from 'react';
import { Button, Flex, Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
type TableRowSelection = TableProps['rowSelection'];
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const columns: TableColumnsType = [
{ title: 'Name', dataIndex: 'name' },
{ title: 'Age', dataIndex: 'age' },
{ title: 'Address', dataIndex: 'address' },
];
const dataSource = Array.from({ length: 46 }).map((_, i) => ({
key: i,
name: `Edward King ${i}`,
age: 32,
address: `London, Park Lane no. ${i}`,
}));
const App: React.FC = () => {
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [loading, setLoading] = useState(false);
const start = () => {
setLoading(true);
// ajax request after empty completing
setTimeout(() => {
setSelectedRowKeys([]);
setLoading(false);
}, 1000);
};
const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
console.log('selectedRowKeys changed: ', newSelectedRowKeys);
setSelectedRowKeys(newSelectedRowKeys);
};
const rowSelection: TableRowSelection = {
selectedRowKeys,
onChange: onSelectChange,
};
const hasSelected = selectedRowKeys.length > 0;
return (
Reload
{hasSelected ? `Selected ${selectedRowKeys.length} items` : null}
rowSelection={rowSelection} columns={columns} dataSource={dataSource} />
);
};
export default App;
```
### 自定义选择项
通过 `rowSelection.selections` 自定义选择项,默认不显示下拉选项,设为 `true` 时显示默认选择项。
```tsx
import React, { useState } from 'react';
import { Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
type TableRowSelection = TableProps['rowSelection'];
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Age',
dataIndex: 'age',
},
{
title: 'Address',
dataIndex: 'address',
},
];
const dataSource = Array.from({ length: 46 }).map((_, i) => ({
key: i,
name: `Edward King ${i}`,
age: 32,
address: `London, Park Lane no. ${i}`,
}));
const App: React.FC = () => {
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
console.log('selectedRowKeys changed: ', newSelectedRowKeys);
setSelectedRowKeys(newSelectedRowKeys);
};
const rowSelection: TableRowSelection = {
selectedRowKeys,
onChange: onSelectChange,
selections: [
Table.SELECTION_ALL,
Table.SELECTION_INVERT,
Table.SELECTION_NONE,
{
key: 'odd',
text: 'Select Odd Row',
onSelect: (changeableRowKeys) => {
let newSelectedRowKeys = [];
newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
if (index % 2 !== 0) {
return false;
}
return true;
});
setSelectedRowKeys(newSelectedRowKeys);
},
},
{
key: 'even',
text: 'Select Even Row',
onSelect: (changeableRowKeys) => {
let newSelectedRowKeys = [];
newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
if (index % 2 !== 0) {
return true;
}
return false;
});
setSelectedRowKeys(newSelectedRowKeys);
},
},
],
};
return rowSelection={rowSelection} columns={columns} dataSource={dataSource} />;
};
export default App;
```
### 筛选和排序
对某一列数据进行筛选,使用列的 `filters` 属性来指定需要筛选菜单的列,`onFilter` 用于筛选当前数据,`filterMultiple` 用于指定多选和单选,`filterOnClose` 用于指定是否在筛选菜单关闭时触发筛选。
使用 `defaultFilteredValue` 属性,设置列的默认筛选项。
对某一列数据进行排序,通过指定列的 `sorter` 函数即可启动排序按钮。`sorter: function(rowA, rowB) { ... }`, rowA、rowB 为比较的两个行数据。
`sortDirections: ['ascend', 'descend']` 改变每列可用的排序方式,切换排序时按数组内容依次切换,设置在 table props 上时对所有列生效。你可以通过设置 `['ascend', 'descend', 'ascend']` 禁止排序恢复到默认状态。
使用 `defaultSortOrder` 属性,设置列的默认排序顺序。
如果 `sortOrder` 或者 `defaultSortOrder` 的值为 `ascend` 或者 `descend`,则可以通过 `sorter` 的函数第三个参数获取当前排序的状态。该函数可以是 `function(a, b, sortOrder) { ... }` 的形式。
```tsx
import React from 'react';
import { Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
showSorterTooltip: { target: 'full-header' },
filters: [
{
text: 'Joe',
value: 'Joe',
},
{
text: 'Jim',
value: 'Jim',
},
{
text: 'Submenu',
value: 'Submenu',
children: [
{
text: 'Green',
value: 'Green',
},
{
text: 'Black',
value: 'Black',
},
],
},
],
// specify the condition of filtering result
// here is that finding the name started with `value`
onFilter: (value, record) => record.name.indexOf(value as string) === 0,
sorter: (a, b) => a.name.length - b.name.length,
sortDirections: ['descend'],
},
{
title: 'Age',
dataIndex: 'age',
defaultSortOrder: 'descend',
sorter: (a, b) => a.age - b.age,
},
{
title: 'Address',
dataIndex: 'address',
filters: [
{
text: 'London',
value: 'London',
},
{
text: 'New York',
value: 'New York',
},
],
onFilter: (value, record) => record.address.indexOf(value as string) === 0,
},
];
const data = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
age: 32,
address: 'London No. 2 Lake Park',
},
];
const onChange: TableProps['onChange'] = (pagination, filters, sorter, extra) => {
console.log('params', pagination, filters, sorter, extra);
};
const App: React.FC = () => (
columns={columns}
dataSource={data}
onChange={onChange}
showSorterTooltip={{ target: 'sorter-icon' }}
/>
);
export default App;
```
### 树型筛选菜单
可以使用 `filterMode` 来修改筛选菜单的 UI,可选值有 `menu`(默认)和 `tree`。
```tsx
import React from 'react';
import { Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
filters: [
{
text: 'Joe',
value: 'Joe',
},
{
text: 'Category 1',
value: 'Category 1',
children: [
{
text: 'Yellow',
value: 'Yellow',
},
{
text: 'Pink',
value: 'Pink',
},
],
},
{
text: 'Category 2',
value: 'Category 2',
children: [
{
text: 'Green',
value: 'Green',
},
{
text: 'Black',
value: 'Black',
},
],
},
],
filterMode: 'tree',
filterSearch: true,
onFilter: (value, record) => record.name.includes(value as string),
width: '30%',
},
{
title: 'Age',
dataIndex: 'age',
sorter: (a, b) => a.age - b.age,
},
{
title: 'Address',
dataIndex: 'address',
filters: [
{
text: 'London',
value: 'London',
},
{
text: 'New York',
value: 'New York',
},
],
onFilter: (value, record) => record.address.startsWith(value as string),
filterSearch: true,
width: '40%',
},
];
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
age: 32,
address: 'London No. 2 Lake Park',
},
];
const onChange: TableProps['onChange'] = (pagination, filters, sorter, extra) => {
console.log('params', pagination, filters, sorter, extra);
};
const App: React.FC = () => (
columns={columns} dataSource={data} onChange={onChange} />
);
export default App;
```
### 自定义筛选的搜索
`filterSearch` 用于开启筛选项的搜索,通过 `filterSearch:(input, record) => boolean` 设置自定义筛选方法
```tsx
import React from 'react';
import { Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
interface DataType {
key: React.Key;
name: string;
age: number;
address: string;
}
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
filters: [
{
text: 'Joe',
value: 'Joe',
},
{
text: 'Category 1',
value: 'Category 1',
},
{
text: 'Category 2',
value: 'Category 2',
},
],
filterMode: 'tree',
filterSearch: true,
onFilter: (value, record) => record.name.startsWith(value as string),
width: '30%',
},
{
title: 'Age',
dataIndex: 'age',
sorter: (a, b) => a.age - b.age,
},
{
title: 'Address',
dataIndex: 'address',
filters: [
{
text: 'London',
value: 'London',
},
{
text: 'New York',
value: 'New York',
},
],
onFilter: (value, record) => record.address.startsWith(value as string),
filterSearch: true,
width: '40%',
},
];
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
age: 32,
address: 'London No. 2 Lake Park',
},
];
const onChange: TableProps['onChange'] = (pagination, filters, sorter, extra) => {
console.log('params', pagination, filters, sorter, extra);
};
const App: React.FC = () => (
columns={columns} dataSource={data} onChange={onChange} />
);
export default App;
```
### 多列排序
`column.sorter` 支持 `multiple` 字段以配置多列排序优先级。通过 `sorter.compare` 配置排序逻辑,你可以通过不设置该函数只启动多列排序的交互形式。
```tsx
import React from 'react';
import { Table } from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
interface DataType {
key: React.Key;
name: string;
chinese: number;
math: number;
english: number;
}
const columns: TableColumnsType = [
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Chinese Score',
dataIndex: 'chinese',
sorter: {
compare: (a, b) => a.chinese - b.chinese,
multiple: 3,
},
},
{
title: 'Math Score',
dataIndex: 'math',
sorter: {
compare: (a, b) => a.math - b.math,
multiple: 2,
},
},
{
title: 'English Score',
dataIndex: 'english',
sorter: {
compare: (a, b) => a.english - b.english,
multiple: 1,
},
},
];
const data: DataType[] = [
{
key: '1',
name: 'John Brown',
chinese: 98,
math: 60,
english: 70,
},
{
key: '2',
name: 'Jim Green',
chinese: 98,
math: 66,
english: 89,
},
{
key: '3',
name: 'Joe Black',
chinese: 98,
math: 90,
english: 70,
},
{
key: '4',
name: 'Jim Red',
chinese: 88,
math: 99,
english: 89,
},
];
const onChange: TableProps['onChange'] = (pagination, filters, sorter, extra) => {
console.log('params', pagination, filters, sorter, extra);
};
const App: React.FC = () => (
columns={columns} dataSource={data} onChange={onChange} />
);
export default App;
```
### 可控的筛选和排序
使用受控属性对筛选和排序状态进行控制。
> 1. columns 中定义了 filteredValue 和 sortOrder 属性即视为受控模式。
> 2. 只支持同时对一列进行排序,请保证只有一列的 sortOrder 属性是生效的。
> 3. 务必指定 `column.key`。
```tsx
import React, { useState } from 'react';
import type { TableColumnsType, TableProps } from 'antd';
import { Button, Space, Table } from 'antd';
type OnChange = NonNullable['onChange']>;
type Filters = Parameters[1];
type GetSingle = T extends (infer U)[] ? U : never;
type Sorts = GetSingle