npm i @rtdui/notifications
tip: 记得安装
@rtdui/hooks和@rtdui/core配对依赖, 如果还未安装的话.
使用命令方式显示通知, 通知默认显示在页面的右下角
首先, 要求在App顶层中添加Notifications组件, 注意该组件必须有且只有一次. 通常作为React项目根组件的第一个孩子, 如:
import { Notifications } from "@rtdui/notifications";
<App>
<Notifications limit={5} autoClose={4000} />
</App>;
Notifications组件内部使用了队列功能, limit属性控制着可以同时显示的通知数量(默认为5), 超过限制时会在队列中排队.
Notifications组件的autoClose属性控制着通知自动关闭的毫秒数(默认为4000), 通知的自身选项可以覆盖默认的自动关闭时间, 也可以禁用自动关闭功能.
之后就可以在App内的任意位置通过命令显示任意通知:
import { notifications } from "@rtdui/notifications";
<button
onClick={() =>
notifications.show({
title: "Title",
content: "Message", // 可以是任意React可以渲染的内容, 如React元素
})
}
>
Open
</button>;
默认使用Notifications组件设置的自动关闭时间, 通知选项可以覆盖默认自动关闭时间
import { notifications } from "@rtdui/notifications";
notifications.show({
title: "Title",
content: "Message",
autoClose: 8000, // 8秒后自动关闭
});
notifications.show({
title: "Title",
content: "Message",
autoClose: false, // 禁止自动关闭
});
支持对已显示的通知进行更新, 前提是必须获取或指定通知的id, 因为更新消息必须要指定id.
import { notifications } from "@rtdui/notifications";
// show()方法会返回自动生成的id, 将它保存起来
const myId = notifications.show({
title: "Title",
content: "Processing",
autoClose: false, // 禁止自动关闭
});
notifications.update({
id: myId, // 更新指定id的通知
title: "Title",
content: "Success",
autoClose: 4000, // 更新可以开启自动关闭
});
// 或者在show方法的选项参数中手动指定id
notifications.show({
id: "my-id", // 手动指定id
title: "Title",
content: "Processing",
autoClose: false, // 禁止自动关闭
});
notifications.update({
id: "my-id", // 更新指定id的通知
title: "Title",
content: "Success",
autoClose: 4000, // 更新可以开启自动关闭
});| 属性名 | 类型 | 是否必须 | 默认值 | 说明 |
|---|---|---|---|---|
| children | React.ReactNode | no | Notification message, place main text here | |
| color | "primary" | "secondary" | "accent" | "info" | "success" | "warning" | "error" | "transparent" | undefined | no | Notification color | |
| icon | React.ReactNode | no | Notification icon, replaces color line | |
| loading | boolean | undefined | no | Replaces colored line or icon with Loader component | |
| onClose | (() => void) | undefined | no | Called when close button is clicked | |
| slots | { icon?: string | undefined; title?: string | undefined; content?: string | undefined; closeBtn?: string | undefined; } | undefined | no | ||
| title | React.ReactNode | no | Notification title, displayed before body | |
| withCloseButton | boolean | undefined | no | Determines whether close button should be visible, true by default |