Basic Toast
A transient, auto-dismissing confirmation announced politely.
6 个框架中级
A capped queue of toasts sharing one live region.
<!--
A stack is a queue with a cap. Three things make it different from N copies of
a single toast:
1. The cap. Unbounded stacks are how a retry loop covers the whole screen.
Overflow waits its turn rather than rendering.
2. One region, N children. The live region is the container - announcing each
toast means appending into the SAME mounted region, not mounting a region
per toast.
3. Newest first, visually - but appended last in the DOM, so reading order
matches the queue. column-reverse keeps those two facts independent.
-->
<div class="toast-stack" role="status" aria-live="polite"></div>
<script>
const MAX_VISIBLE = 3;
const stack = document.querySelector('.toast-stack');
const queue = [];
function render() {
stack.replaceChildren();
queue.slice(0, MAX_VISIBLE).forEach((toast) => {
const el = document.createElement('div');
el.className = 'toast';
el.innerHTML =
'<p class="toast__title"></p><button class="toast__close" type="button" aria-label="Dismiss">×</button>';
el.querySelector('.toast__title').textContent = toast.title;
el.querySelector('.toast__close').addEventListener('click', () => dismiss(toast.id));
stack.append(el);
});
}
function dismiss(id) {
const index = queue.findIndex((t) => t.id === id);
if (index > -1) queue.splice(index, 1);
render();
}
function push(title, duration = 5000) {
const id = crypto.randomUUID();
queue.unshift({ id, title });
render();
setTimeout(() => dismiss(id), duration);
}
</script>| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
items必填 | ToastItem[] | - | 要渲染的项目数组。 |
onDismiss | (id: string) => void | - | 用户关闭通知时触发。 |
dismissLabel | string | 'Dismiss' | 关闭按钮的无障碍名称。 |
className | string | - | 合并到根元素上的额外类名。 |
The cap is the part to tune, and the part not to remove - three is a sensible default and unbounded is how a failing retry loop covers the viewport. Overflow should wait its turn rather than render. Consider collapsing duplicates into a count ("Retrying - 4 times") instead of stacking identical strings, which is both quieter and more informative. The whole stack lives in one region: adding a region per toast means adding a race per toast.