zzzUI

Toast

滑入右下角、随后自动消失的简短消息。外观沿用 Alert,外加一圈描边,使其浮于页面之上。

安装

terminal
# once per project: where @zzzui items come frompnpm dlx shadcn@latest registry add @zzzui=https://zzzui.catforest.dev/r/{name}.jsonpnpm dlx shadcn@latest add @zzzui/toast

示例

两条消息,其中一条带操作按钮

toast-basic.tsx
import { Button } from "@/components/zero/button";import { ToastProvider, useToast } from "@/components/zero/toast";function TakeJob() {  const toast = useToast();  return (    <div className="flex flex-wrap gap-3">      <Button        onClick={() =>          toast.add({            type: "success",            title: "Job taken",            description: "Reach the north gate before 22:00.",          })        }      >        Take the job      </Button>      <Button        variant="secondary"        onClick={() =>          toast.add({            type: "warning",            title: "Low on fuel",            description: "Refuel before you take the next job.",            actionProps: { children: "Find a pump" },          })        }      >        Check the tank      </Button>    </div>  );}export default function ToastBasic() {  return (    <ToastProvider>      <TakeJob />    </ToastProvider>  );}

行为

在应用外层包裹一次 ToastProvider,其内任意位置调用 useToast().add({ title, description, type }) 即可显示一条消息。type 取 Alert 的四种色调之一,actionProps 用于添加按钮。

每条消息在五秒后消失,指针悬停或获得焦点期间暂停计时。向右滑动或点击关闭按钮可提前关闭,其余消息随即补上空位。同时最多显示三条,最新的一条最靠近角落,多出的依次排队。每条消息出现时以 polite 方式通知读屏软件。

属性

ToastProvider

属性类型默认值说明
timeoutnumber5000消息消失前的毫秒数;设为 0 则不自动消失。
limitnumber3同时显示的最大数量。
closeLabelstring"Close"每条提示的关闭按钮的可访问名称。

另可传入 Base UI Toast.Provider 的全部属性。

useToast

属性类型默认值说明
add(options) => string—显示一条消息,可传入 title、description、type、timeout、actionProps;返回该消息的 id。
close(id?) => void—关闭指定的一条消息,或全部关闭。
update(id, options) => void—修改正在显示的消息。
promise(promise, options) => Promise—跟随 promise 状态变化的消息:从加载中到成功或出错。

另可传入 Base UI useToastManager 的全部属性。