跳转到内容

Message 全局提示

何时使用

  • 可提供成功、警告和错误等反馈信息。
  • 顶部居中显示并自动消失,是一种不打断用户操作的轻量级提示方式。

代码演示

Hooks 调用(推荐)

loading

其他提示类型

loading

修改延时

loading

加载中

loading

Promise 接口

loading

自定义样式

loading

更新消息内容

loading

静态方法(不推荐)

loading

API

组件提供了一些静态方法,使用方式和参数如下:

  • message.success(content, [duration], onClose)
  • message.error(content, [duration], onClose)
  • message.info(content, [duration], onClose)
  • message.warning(content, [duration], onClose)
  • message.loading(content, [duration], onClose)
参数说明类型默认值
content提示内容VNode | config-
duration自动关闭的延时,单位秒。设为 0 时不自动关闭number3
onClose关闭时触发的回调函数function-

组件同时提供 promise 接口。

  • message[level](content, [duration]).then(afterClose)
  • message[level](content, [duration], onClose).then(afterClose)

其中 message[level] 是组件已经提供的静态方法。then 接口返回值是 Promise。

也可以对象的形式传递参数:

  • message.open(config)
  • message.success(config)
  • message.error(config)
  • message.info(config)
  • message.warning(config)
  • message.loading(config)

config 对象属性如下:

| 参数 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | --- | | class | 自定义 CSS class | string | - | | content | 提示内容 | VNode | - | | duration | 自动关闭的延时,单位秒。设为 0 时不自动关闭 | number | 3 | | icon | 自定义图标 | VNode | - | | pauseOnHover | 悬停时是否暂停计时器 | boolean | true | - | | key | 当前提示的唯一标志 | string | number | - | | style | 自定义内联样式 | CSSProperties | - | | onClick | 点击 message 时触发的回调函数 | function | - | | onClose | 关闭时触发的回调函数 | function | - |

全局方法

还提供了全局配置和全局销毁方法:

  • message.config(options)
  • message.destroy()

也可通过 message.destroy(key) 来关闭一条消息。

message.config

当你使用 ConfigProvider 进行全局化配置时,系统会默认自动开启 RTL 模式。(4.3.0+)

当你想单独使用,可通过如下设置开启 RTL 模式。

js
message.config({
  top: 100,
  duration: 2,
  maxCount: 3,
  rtl: true,
  prefixCls: 'my-message',
});
参数说明类型默认值版本
duration默认自动关闭延时,单位秒number3
getContainer配置渲染节点的输出位置,但依旧为全屏展示() => HTMLElement() => document.body
maxCount最大显示数,超过限制时,最早的消息会被自动关闭number-
prefixCls消息节点的 class 前缀stringant-message4.5.0
rtl是否开启 RTL 模式booleanfalse
top消息距离顶部的位置string | number8

FAQ

为什么 message 不能获取 context、redux 的内容和 ConfigProvider 的 locale/prefixCls/theme 等配置?

直接调用 message 方法,antd 会通过 ReactDOM.render 动态创建新的 React 实体。其 context 与当前代码所在 context 并不相同,因而无法获取 context 信息。

异同:通过 hooks 创建的 contextHolder 必须插入到子元素节点中才会生效,当你不需要上下文信息时请直接调用。

可通过 App 包裹组件 简化 useMessage 等方法需要手动植入 contextHolder 的问题。

静态方法如何设置 prefixCls ?

你可以通过 ConfigProvider.config 进行设置。

基于 MIT 许可发布