安装

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, // 更新可以开启自动关闭
});