Notification
Notificaciones globales: posiciones, tiempo de visualización, acciones, actualización y cola.
Cuándo usar
notification Muestra el evento con un encabezado, detalles y acciones adicionales. Es adecuado para la exportación de fondo, operación a largo plazo o mensaje de aplicación. Para una respuesta corta, Message es suficiente; Importante advertencia persistente también publica principalmente contenido.
CSS Prefijo de notificación Mostrar total ConfigProvider.prefixCls y Local prefixCls sin restablecimiento de estado. NotificationHolder Cambia las clases de todas las ubicaciones y partes de la tarjeta. App Usos notification.prefixCls. Se conservan colas, temporizadores, foco y superficie nativa.
instancia, contenido y posición
crear createNotification y colocar uno NotificationHolder dentro del ConfigProvider deseado. La instancia tiene una cola independiente para todas las disposiciones; Las áreas individuales necesitan instancias separadas.
| Tarea | Oportunidad | Ejemplo |
|---|---|---|
| Mostrar evento detallado | open, title, description |
Notificación principal |
| Seleccionar estado semántico | success/info/warning/error |
Tipos |
| Mostrar tiempo hasta el cierre | duration, showProgress, pauseOnHover |
Tiempo de visualización |
| Lista de colapso en una posición | stack |
Pila de notificación |
| Seleccionar posición y contenedor | placement, getContainer |
Ubicación |
| Reemplazar la espera con el resultado | Mismo key, actions |
Actualización |
| Realizar una tarea en segundo plano | Modelo de aplicación | informe de exportación |
En title y description puede transferir texto, número o fragmento. Para botones y enlaces use actions. Propiedad placement Especifica una de las seis posiciones relativas a los bordes de la pantalla. Si establece rtl, el texto irá de derecha a izquierda y el borde seleccionado seguirá siendo el mismo.
Tiempo de actualización y visualización
Repetido open con el mismo key Actualice la entrada, incluyendo texto, actions, type y placement. Para guardar la descripción de DOM Al cambiar el estado, configure type al abrir, por ejemplo info: La apariencia o eliminación del icono puede volver a crear el contenedor de contenido.
De forma predeterminada, la notificación se cierra después de 4,5 segundos. duration: 0 o duration: false lo deja abierto. con una duración positiva showProgress muestra el tiempo restante. La barra se detiene con el temporizador cuando el usuario coloca el puntero cuando pauseOnHover se enciende o mueve el foco dentro de la tarjeta. En Ejemplo de exportación Componente Progress muestra qué parte del informe está lista.
Con closable Puede cambiar el icono, la etiqueta o el botón de cierre. Si oculta el botón en la notificación constante, proporcione su propia acción de cierre. onClose Dispara al comienzo de la tarjeta, y onAllRemoved cuando la última carta desaparezca del DOM.
Por defecto, la cuarta carta en una posición contrae la lista. El apuntar o enfocar dentro de la pila revela todas las cartas. El umbral se puede cambiar a través de stack.threshold y stack: false deja la lista abierta. Si desea cerrar las notificaciones más antiguas, configure maxCount. Este límite es válido para todas las posiciones de instancia a la vez.
Contexto, diseño y limitaciones
El titular recibe un tema y dirección locales de ConfigProvider. theme.components.Notification Cambios width, zIndexPopup y antecedentes de estado sin reapertura. Local CSS El titular de las variables y los registros tienen prioridad.
Sin fondos de estado de anulación de componentes Use colorBgElevated en lugar de colorInfoBg/colorSuccessBg. La configuración vacía devuelve un ancho estándar de 384px. explícito width:undefined - un caso separado; Para un tamaño determinado, use el número o CSS longitud sin asumir el modo max-content.
Para los botones y enlaces disponibles, use actions. Mediante props Puedes asignar una tarjeta HTML- Atributos, por ejemplo data-* o Aria. onClick Obtiene un evento de clic en la tarjeta. El botón de cerrar tiene un controlador separado.
A través de ConfigProvider.notification, puede establecer un icono de cierre común, clases y estilos. Parámetros classNames y styles Aceptar un objeto o función de { props }. La configuración del proveedor, la instancia y la tarjeta se aplican en este orden. Ejemplo de diseño.
getContainer Llamado en el navegador. Si la función no devolvió el nodo, la biblioteca usa ConfigProvider.getPopupContainer, luego document.body. Si faltan ambas funciones, la lista permanece junto al titular.
En lugar de un par manual createNotification/NotificationHolder puede usar App: App.useApp() devuelve notification del área más cercana. Sus valores predeterminados se heredan por campos, mientras que las colas principales y anidadas son independientes. Cambio App.notification.placement se aplica a las nuevas notificaciones.
Ejemplos
Notificación regular
createNotification y un soporte.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
</script>
<NotificationHolder {notification} top={240} id="notification-basic-notices" />
<Button onclick={() => notification.open(({
title: "Documentación actualizada",
description: "Aparecieron nuevos ejemplos de componentes en el catálogo."
}))}>{("Mostrar notificación regular")}</Button>
Estándar
success, info, warning y error.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
const types = ['success', 'info', 'warning', 'error'] as const;
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-types-notices" />
<div class="actions">{#each types as type (type)}
<Button onclick={() => notification[type](({
key: type,
title: `Estado: ${type}`,
description: "Icono de estado estándar.",
duration: 0
}))}>{(type)}</Button>
{/each}<Button
onclick={() => notification.destroy()}
>{("Eliminar notificaciones de tipo")}</Button></div>
Tiempo de visualización
La banda muestra cuánto tiempo queda antes del cierre.
<script lang="ts">
import {
Button,
Checkbox,
InputNumber,
NotificationHolder,
createNotification
} from '@woodger/antd';
const notification = createNotification();
let duration = $state(4.5);
let permanent = $state(false);
let pauseOnHover = $state(true);
let showProgress = $state(true);
let closed = $state(0);
</script>
<style>
.settings {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
}
output {
display: block;
margin-top: 16px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-duration-notices" />
<div class="settings">
<InputNumber
aria-label={("Notificación de duración")}
min={0}
max={10}
step={0.5}
value={duration}
onValueChange={next => { duration = next ?? 0; }}
/>
<Checkbox bind:checked={permanent}>{("Sin cierre automático")}</Checkbox>
<Checkbox bind:checked={showProgress} disabled={permanent || duration === 0}>
{("Mostrar el tiempo restante")}
</Checkbox>
<Checkbox
bind:checked={pauseOnHover}
>{("Pausa de notificación al pasar el cursor")}</Checkbox>
<Button onclick={() => notification.info(({
key: 'duration',
title: "Tiempo de visualización",
description: "Pase el puntero o navegue hasta el botón Cerrar.",
duration: permanent ? false : duration,
pauseOnHover,
showProgress,
onClose: () => { closed++; }
}))}>{("Mostrar con duración seleccionada")}</Button>
</div>
<output
aria-label={("Notificación de cierre")}
>{("Cerrado: ")}{closed}</output>
Su cierre
Texto Nombre disponible, disabled y botón oculto.
<script lang="ts">
import { Button, Checkbox, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification({ placement: 'bottomLeft' });
let disabled = $state(false);
let hidden = $state(false);
</script>
<style>
.settings {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-close-notices" />
<div
class="settings"
><Checkbox
bind:checked={disabled}
>{("Deshabilitar el botón Cerrar")}</Checkbox>
<Checkbox bind:checked={hidden}>{("Ocultar cierre de botón")}</Checkbox>
<Button onclick={() => notification.open(({
key: 'close',
title: "Su cierre",
description: "Se aplican ajustes al grabar o actualizar una entrada.",
duration: 0,
closable: hidden ? false : {
disabled,
closeIcon: "Listo",
'aria-label': "Notificación completa"
}
}))}>{("Mostrar su cierre")}</Button>
<Button
onclick={() => notification.destroy('close')}
>{("Eliminar notificación manualmente")}</Button></div>
Su icono y diseño
Diseño general del título y marco, su propio icono de color para una tarjeta.
<script lang="ts">
import { Button, ConfigProvider, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
const appearance = {
classNames: { title: 'notification-custom-title' },
styles: { root: 'border: 1px dashed var(--ant-color-warning)' }
};
function showNotice() {
notification.open({
title: ("Diseño propio"),
description,
icon,
duration: 5,
class: 'notification-custom',
styles: {
root: 'border-radius: 12px',
icon: 'color: var(--ant-color-warning)'
}
});
}
</script>
<style>
:global(.notification-custom-title) { font-weight: 600; }
</style>
{#snippet icon()}<span aria-hidden="true">★</span>{/snippet}
{#snippet description()}
<span>{("etiqueta de ")}<strong>Svelte Snippet</strong>{(" con diseño propio.")}</span>
{/snippet}
<ConfigProvider notification={appearance}>
<NotificationHolder {notification} top={240} id="notification-custom-notices" />
<Button onclick={showNotice}>{("Mostrar su icono de notificación")}</Button>
</ConfigProvider>
Posiciones
Seis posiciones de pantalla, selección de contenedores y dirección de texto.
<script lang="ts">
import {
Button,
Checkbox,
NotificationHolder,
RadioGroup,
createNotification,
type NotificationPlacement
} from '@woodger/antd';
const notification = createNotification();
const placements: NotificationPlacement[] = [
'top', 'topLeft', 'topRight', 'bottom', 'bottomLeft', 'bottomRight'
];
let placement = $state<NotificationPlacement>('topRight');
let container = $state<HTMLDivElement>();
let rtl = $state(false);
</script>
<style>
.settings {
display: grid;
gap: 20px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<NotificationHolder {notification} rtl={rtl || undefined} getContainer={() => container}
top={240} bottom={24} id="notification-placement-notices" />
<div bind:this={container} class="settings">
<RadioGroup
aria-label={("Notificación de posición de ejemplo")}
bind:value={placement}
options={(placements)}
/>
<Checkbox bind:checked={rtl}>{("Texto de derecha a izquierda")}</Checkbox>
<div class="actions"><Button onclick={() => notification.info(({
key: placement,
title: `Posición: ${placement}`,
description: "Área de pantalla física.",
placement,
duration: 0
}))}>{("Mostrar en la posición seleccionada")}</Button>
<Button
onclick={() => notification.destroy()}
>{("Notificación clara")}</Button></div></div>
Actualización y acciones
Uno key Nuevo resultado y botón de aceptación.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification();
let accepted = $state(0);
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
output {
display: block;
margin-top: 16px;
}
</style>
{#snippet actions()}<Button type="primary" onclick={() => {
accepted++;
notification.destroy('review');
}}>{("Aceptar resultado de notificación")}</Button>{/snippet}
<NotificationHolder {notification} top={240} id="notification-update-notices" />
<div class="actions">
<Button onclick={() => notification.info(({
key: 'review',
title: "Comprobar el documento",
description: "Espere el resultado de una prueba.",
duration: 0
}))}>{("INICIO DE NOTIFICACIÓN DE VERIFICACIÓN")}</Button>
<Button onclick={() => notification.success(({
key: 'review',
title: "Documento verificado",
description: "Puede aceptar el resultado.",
actions,
duration: 0
}))}>{("Completar la notificación de verificación")}</Button>
<Button onclick={() => notification.destroy('review')}>
{("Eliminar comprobación de notificación")}
</Button>
</div>
<output
aria-label={("Notificación")}
>{("Recibido: ")}{accepted}</output>
Límite de cola
Cuando se agrega la cuarta notificación, se cierra la más antigua.
<script lang="ts">
import { Button, NotificationHolder, createNotification } from '@woodger/antd';
const notification = createNotification({ maxCount: 3, duration: 0, placement: 'bottomLeft' });
let sequence = $state(0);
</script>
<style>
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
</style>
<NotificationHolder {notification} top={240} id="notification-queue-notices" />
<div class="actions"><Button onclick={() => notification.info(({
title: `Notificación de cola No.${++sequence}`,
description: "Límite total es de tres entradas."
}))}>{("Añadir a la cola de notificación")}</Button>
<Button
onclick={() => notification.destroy()}
>{("Borrar notificación de cola")}</Button></div>
Pila de notificación
Añadir cuatro informes. Apunte el puntero o mueva el foco a la pila.
<script lang="ts">
import {
Button, Checkbox, Flex, InputNumber, NotificationHolder, createNotification
} from '@woodger/antd';
const thresholdId = $props.id();
const notification = createNotification({ duration: 0, placement: 'bottomRight' });
let enabled = $state(true);
let threshold = $state(3);
let hasReports = $state(false);
let sequence = 0;
function reportReady() {
sequence += 1;
notification.success({
title: ("INFORME LISTO"),
description: `report-${sequence}.csv`
});
hasReports = true;
}
</script>
<NotificationHolder {notification} stack={enabled ? { threshold } : false}
onAllRemoved={() => { hasReports = false; }} />
<Flex vertical align="start" gap="medium">
<Flex align="center" wrap gap="small">
<Checkbox bind:checked={enabled}>{("Colapso")}</Checkbox>
<label for={thresholdId}>{("Umbral de colapso")}</label>
<InputNumber id={thresholdId} value={threshold} min={1} max={10} step={1} precision={0}
disabled={!enabled} onValueChange={value => { threshold = value ?? 1; }} />
</Flex>
<Flex wrap gap="small">
<Button type="primary" onclick={reportReady}>
{("Informe el informe terminado")}
</Button>
<Button disabled={!hasReports} onclick={() => notification.destroy()}>
{("Notificaciones claras")}
</Button>
</Flex>
</Flex>
Tema del componente notification
Ancho, Fondo de Estado y Capa. Cambiar tema Guarda el comentario en actions, cola y hora de cierre.
<script lang="ts">
import {
Button,
Checkbox,
ConfigProvider,
Input,
NotificationHolder,
RadioGroup,
createNotification
} from '@woodger/antd';
import type { NotificationType } from '@woodger/antd';
const notification = createNotification({ pauseOnHover: false });
let enabled = $state(true);
let resetWidth = $state(false);
let status = $state<NotificationType>('info');
let comment = $state(("borrador de comentarios"));
const types = ['info', 'success', 'warning', 'error'] as const;
const tokens = {
zIndexPopup: 2400,
progressBg: '#d48806',
colorInfoBg: '#fffbe6',
colorSuccessBg: '#f6ffed',
colorWarningBg: '#fff7e6',
colorErrorBg: '#fff1f0'
};
</script>
<style>
.settings {
display: grid;
gap: 24px;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.status-settings, .notice-actions {
display: grid;
gap: 12px;
min-width: 0;
max-width: 100%;
}
label {
display: grid;
gap: 8px;
}
</style>
{#snippet actions()}
<div class="notice-actions">
<label>{("Comentario\n ")}<Input bind:value={comment} aria-label={("Comentario del hilo de notificación")} />
</label>
<Button onclick={() => notification.destroy('theme')}>{("Listo")}</Button>
</div>
{/snippet}
<ConfigProvider direction="rtl" theme={{
cssVar: { prefix: 'notification-demo' },
token: { colorInfoBg: '#fffbe6' },
components: { Notification: enabled ? { ...tokens, width: resetWidth ? undefined : 480 } : {} }
}}>
<NotificationHolder {notification} top={240} bottom={24} id="notification-theme-notices" />
<div class="settings">
<Checkbox bind:checked={enabled}>{("Aplicar notificación de tokens")}</Checkbox>
<Checkbox bind:checked={resetWidth} disabled={!enabled}>
{("Ancho de transferencia: Undefined")}
</Checkbox>
<div class="status-settings">
<span>{("Estado de notificación")}</span>
<RadioGroup
aria-label={("Notificación de estado del tema")}
bind:value={status}
options={(types)}
style="
display: flex;
flex-wrap: wrap;
gap: 8px;
"
/>
</div>
<div class="actions">
<Button onclick={() => notification.open(({
key: 'theme', type: status, title: "Tema de notificación",
description: "El tema se actualiza sin un comentario y reinicio de acción.", actions, duration: 0
}))}>{("Comprobar tema")}</Button>
<Button onclick={() => notification.info(({
key: 'timed-theme', title: "Notificación durante dos segundos",
description: "El cambio de tema no renueva la pantalla.", duration: 2, showProgress: true,
class: 'notification-theme-timed'
}))}>{("mostrar durante 2 segundos")}</Button>
</div>
</div>
</ConfigProvider>
informe de exportación
Operación de progreso, éxito, error, repetición, cancelación y CSV real.
NotificationExample.svelte<script lang="ts"> import { onDestroy } from 'svelte'; import { Button, Checkbox, NotificationHolder, Progress, Select, createNotification, type NotificationPlacement } from '@woodger/antd'; import { createNotificationExport } from './notification-export.model.svelte'; const notification = createNotification({ maxCount: 3 }); let failNext = $state(false); let placement = $state<NotificationPlacement>('topRight'); let result = $state(("Preparar el informe y descargarlo de la notificación.")); let downloadUrl: string | undefined; const placements = ['top', 'topLeft', 'topRight', 'bottom', 'bottomLeft', 'bottomRight'].map( (value) => ({ value: value as NotificationPlacement, label: value }) ); const model = createNotificationExport({ onReady() { result = ("El informe está listo para descargar."); notification.success( ({ key: 'export', title: "INFORME LISTO", description: progress, placement, duration: 0, actions: ready, role: 'status' }) ); }, onError() { result = ("No se pudo preparar un informe. inténtalo de nuevo."); notification.error( ({ key: 'export', title: "Incapaz de preparar el informe", description: progress, placement, duration: 0, actions: retry }) ); } }); function releaseDownload() { if (downloadUrl) URL.revokeObjectURL(downloadUrl); downloadUrl = undefined; } function start() { const failed = failNext; if (!model.start(failed)) { return; } failNext = false; releaseDownload(); result = ("Preparar un informe…"); notification.info( ({ key: 'export', title: "Preparar un informe", description: progress, actions: pending, placement, duration: 0, role: 'status' }) ); } function cancel() { if (!model.cancel()) { return; } result = ("Exportación cancelada."); notification.info( ({ key: 'export', title: "Exportación cancelada", description: progress, placement, duration: 0, actions: retry, role: 'status' }) ); } function download() { const report = model.report; if (!report) { return; } releaseDownload(); downloadUrl = URL.createObjectURL(new Blob([report], { type: 'text/csv;charset=utf-8' })); const link = document.createElement('a'); link.href = downloadUrl; link.download = 'report.csv'; document.body.append(link); link.click(); link.remove(); result = ("Informe descargado."); } function reset() { model.reset(); releaseDownload(); notification.destroy(); result = ("Restablecimiento de ejemplo de exportación."); } onDestroy(() => { model.destroy(); releaseDownload(); }); </script> <style> .actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; } .placement { width: 180px; } output { display: block; margin-top: 20px; color: var(--ant-color-text-secondary); } .phase { margin-block: 0 var(--ant-margin-sm); } </style> {#snippet progress()}<p class="phase">{(model.phase)}</p><Progress percent={model.percent} status={model.status === 'preparing' ? 'active' : model.status === 'error' ? 'exception' : undefined} aria-label={("Preparación del informe")} />{/snippet} {#snippet pending()}<Button onclick={cancel}>{("Cancelar exportación")}</Button>{/snippet} {#snippet retry()}<Button type="primary" onclick={start} >{("Repetir exportación")}</Button>{/snippet} {#snippet ready()} <span class="actions"><Button type="primary" onclick={download}> {("Descargar Reporte")} </Button><Button onclick={() => notification.destroy('export')} >{("Cerrar resultado de exportación")}</Button></span> {/snippet} <NotificationHolder {notification} id="showcase-notifications" /> <div class="actions" ><Button type="primary" loading={model.status === 'preparing'} onclick={start} >{("informe de exportación")}</Button><Checkbox bind:checked={failNext} >{("Siguiente error de exportación")}</Checkbox><div class="placement" ><Select aria-label={("Notificación")} bind:value={placement} options={(placements)} /></div><Button onclick={reset} >{("Ejemplo de notificación de restablecimiento")}</Button></div> <output aria-label={("Resultado de la notificación")}>{result}</output>notification-export.model.svelte.tstype ExportState = | { status: 'idle'; percent: 0; phase: string } | { status: 'preparing'; percent: number; phase: string } | { status: 'ready'; percent: 100; phase: string; report: string } | { status: 'error' | 'cancelled'; percent: number; phase: string }; export function createNotificationExport(callbacks: { onReady: () => void; onError: () => void }) { let state = $state.raw<ExportState>({ status: 'idle', percent: 0, phase: "Preparar un informe." }); let generation = 0; let active = true; const timers = new Set<ReturnType<typeof setTimeout>>(); function clear() { generation++; for (const timer of timers) clearTimeout(timer); timers.clear(); } function start(failed = false): boolean { if (!active || state.status === 'preparing') { return false; } clear(); const current = generation; state = { status: 'preparing', percent: 0, phase: "Después de la preparación, aparecerá aquí el botón de descarga." }; function schedule(delay: number, update: () => void) { const timer = setTimeout( () => { timers.delete(timer); if (active && current === generation && state.status === 'preparing') update(); }, delay ); timers.add(timer); } for (const stage of [ { delay: 200, percent: 25, phase: "Recopilar datos…" }, { delay: 450, percent: 65, phase: "Formando CSV..." }, { delay: 600, percent: 90, phase: "Verificar archivo…" } ]) { schedule( stage.delay, () => { state = { status: 'preparing', percent: stage.percent, phase: stage.phase }; } ); } schedule(700, () => { if (failed) { state = { status: 'error', percent: 90, phase: "Datos almacenados. intente exportar de nuevo." }; callbacks.onError(); } else { state = { status: 'ready', percent: 100, phase: "El archivo CSV contiene dos entradas. Se puede descargar ahora.", report: '\uFEFFname,framework\r\nAnna,Svelte\r\nBoris,TypeScript\r\n' }; callbacks.onReady(); } }); return true; } return { get status() { return state.status; }, get percent() { return state.percent; }, get phase() { return state.phase; }, get report() { return state.status === 'ready' ? state.report : undefined; }, start, cancel() { if (state.status !== 'preparing') { return false; } clear(); state = { status: 'cancelled', percent: state.percent, phase: "Se cancela la preparación del informe." }; return true; }, reset() { clear(); state = { status: 'idle', percent: 0, phase: "Preparar un informe." }; }, destroy() { active = false; clear(); } }; }
NotificationHolder Cambia las clases de todas las ubicaciones y partes de la tarjeta. La aplicación usa la notificación.prefixCls. Se conservan colas, temporizadores, foco y superficie nativa.
CSS Prefijo notification
Espacio de nombres general ConfigProvider y local prefixCls; El estado del componente se guarda al cambiar el nombre.
<script lang="ts">
import {
Checkbox,
ConfigProvider,
NotificationHolder,
createNotification,
Button
} from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-notification' : '');
const notification = createNotification({ duration: 0 });
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Suite de notificaciones de prefijos generales")}</Checkbox>
<Checkbox bind:checked={local}>{("Notificación de prefijo local")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'notification-theme' } }}>
<div class="prefix-stage">
<NotificationHolder {notification} prefixCls={localPrefix} top={240} />
<Button onclick={() => notification.success(({
key: 'prefix',
title: "Notificación Con prefijo",
description: "Cambio de espacio de nombres Guarda la tarjeta actual."
}))}>{("Mostrar notificación con prefijo")}</Button>
<Button onclick={() => notification.destroy()}>
{("Cerrar notificación con prefijo")}
</Button>
</div>
</ConfigProvider>
<output
aria-label={("CSS-prefijo")}
>{("General: ")}{prefix}{("; Local: ")}{(localPrefix
|| ("del proveedor"))}</output>
<p>
{("NotificationHolder Cambia las clases de todas las ubicaciones y partes de la tarjeta. La aplicación usa la notificación.prefixCls. Se conservan colas, temporizadores, foco y superficie nativa.")}
</p>
</div>
API
| Tema | Muestra o restricción |
|---|---|
| Hooks usage (recommended) | Svelte: createNotification y uno NotificationHolder en el contexto correcto. |
| Duration after which the notification box is closed | segundos, false/0 y pausa al pasar el cursor. |
| Notification with icon | Cuatro estados estándar. |
| Custom close button | Su etiqueta, nombre disponible, disabled y botón ocultar. |
| Customized Icon | Icono y descripción de fragmento. |
| Placement | Las seis áreas de pantalla física. |
| Update Message Content | Actualización de software key y acción dentro de la notificación. |
| Stack | Umbral de acumulación y revelación de teclado o desplegable. |
| Show with progress | El indicador de tiempo restante sigue al temporizador de notificación. |
| Customize progress bar color | El color de la banda establece progressBg en el tema notification. |
| Custom semantic styles | Se pueden agregar clases y estilos generales del proveedor para una tarjeta. |
NotificationInstance
| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
open | Crear o actualizar la entrada por key. | (config: NotificationConfig) => void | — |
info | Estado de la información. | (config) => void | info |
success | Operación exitosa. | (config) => void | success |
warning | Prefijo Advertencia. | (config) => void | warning |
error | Error. | (config) => void | error |
destroy | Cierre una entrada o la cola completa. | (key?: string | number) => void | — |
NotificationConfig
| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
title | Encabezado y nombre disponible. | NotificationContent | — |
description | Detalles de notificación. | NotificationContent | — |
actions | Botones y enlaces para otras acciones. | NotificationContent | — |
type | Icono de estado estándar. | success | info | warning | error | — |
icon | Icono propio. | NotificationContent | por tipo |
key | ID de renovación sin registro duplicado. | string | number | generado |
placement | top/bottom, topLeft/topRight, bottomLeft/bottomRight. | NotificationPlacement | topRight |
duration | segundos; false y 0 Apague el temporizador. | number | false | 4.5 |
pauseOnHover | Pausa del temporizador bajo el puntero. | boolean | true |
closable | Ajustes del botón de cierre estándar. | boolean | NotificationClosable | true |
closeIcon | etiqueta propia; false/null Ocultar el botón. | NotificationContent | Cruz |
role | Urgencia del anuncio. | alert | status | alert |
onClose | Inicio de cierre. Devolución de llamada del soporte de desmontaje no. | () => void | — |
class | Clase raíz de entrada. | string | — |
style | CSS Raíz del registro. | string | — |
classNames | Clases de partes individuales de la tarjeta. | NotificationSemantic | — |
styles | Estilos de partes individuales de la tarjeta. | NotificationSemantic | — |
showProgress | Muestra cuánto tiempo queda antes del cierre. | boolean | false |
props | Atributos de la tarjeta nativa que incluyen data-* y ARIA. | NotificationRootAttributes | — |
onClick | Clic en la tarjeta. El botón de cierre se maneja presionando por separado. | (event: MouseEvent) => void | — |
NotificationClosable
| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
disabled | Deshabilitar el botón estándar. | boolean | false |
closeIcon | tiene prioridad sobre closeIcon configuración. | NotificationContent | Cruz |
aria-label | Nombre del botón disponible. | string | locale.closeText |
onClose | Llamado antes onClose Tarjeta cuando se cierra con botón o temporizador. | () => void | — |
createNotification options
| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
placement | Ubicación general de la instancia. | NotificationPlacement | topRight |
duration | Duración total. | number | false | 4.5 |
pauseOnHover | Temporizador de pausa total. | boolean | true |
maxCount | Límite total para todas las ubicaciones. | number | No hay límite |
showProgress | Muestra cuánto tiempo queda antes del cierre. | boolean | false |
prefixCls | Lista completa de prefijos y sus tarjetas. | string | ConfigProvider.prefixCls + "-notification" |
top | Indentación de la superficie superior. | number | 24 |
bottom | hendidura de superficie inferior. | number | 24 |
stack | Umbral de colapso en cada posición. false Deja la lista abierta. | boolean | { threshold?: number } | { threshold: 3 } |
rtl | Dirección del texto. La posición de las tarjetas en la pantalla se establece placement. | boolean | ConfigProvider.direction |
getContainer | Selecciona un nodo para una lista de notificaciones del navegador. | () => HTMLElement | ShadowRoot | null | undefined | — |
closeIcon | Icono de cierre propio para todas las tarjetas. | NotificationContent | ConfigProvider.notification.closeIcon |
classNames | Lista y clases de tarjetas para esta instancia. | NotificationSemantic | — |
styles | Lista y estilos de tarjetas para esta instancia. | NotificationSemantic | — |
onAllRemoved | Llamado después de retirar la última tarjeta del DOM. | () => void | — |
NotificationHolder
| Propiedad | Descripción | Tipo | Predeterminado |
|---|---|---|---|
prefixCls | Lista completa de prefijos y sus tarjetas. | string | ConfigProvider.prefixCls + "-notification" |
top | Indentación de la superficie superior. | number | 24 |
bottom | hendidura de superficie inferior. | number | 24 |
stack | Umbral de colapso en cada posición. false Deja la lista abierta. | boolean | { threshold?: number } | { threshold: 3 } |
rtl | Dirección del texto. La posición de las tarjetas en la pantalla se establece placement. | boolean | ConfigProvider.direction |
getContainer | Selecciona un nodo para una lista de notificaciones del navegador. | () => HTMLElement | ShadowRoot | null | undefined | — |
closeIcon | Icono de cierre propio para todas las tarjetas. | NotificationContent | ConfigProvider.notification.closeIcon |
classNames | Lista y clases de tarjetas para esta instancia. | NotificationSemantic | — |
styles | Lista y estilos de tarjetas para esta instancia. | NotificationSemantic | — |
onAllRemoved | Llamado después de retirar la última tarjeta del DOM. | () => void | — |
notification | copia de cola; Un soporte conectado. | NotificationInstance | Requerido |
id | Identificación de superficie con todas las ubicaciones. | string | — |
class | clase de superficie. | string | — |
style | CSS Superficie. | string | — |
En lugar de React Hook/Métodos estáticos, se utilizan createNotification y NotificationHolder independientes. Retorno de los métodos de apertura void; Cierre ejecuta destroy(key) o botón estándar.
Semantic DOM
Ranuras list y listContent Consulte la lista, el resto a la tarjeta.
| Ranura | CSS-clase | Asignar |
|---|---|---|
list | .ant-notification-list | Grupo separado placement. |
listContent | .ant-notification-list-content | Lista de registros. |
root | .ant-notification-notice | Registro con role Nombre disponible, class/style. |
wrapper | .ant-notification-notice-wrapper | icono y texto; Se crea solo si hay un icono. |
section | .ant-notification-notice-section | pareja title/description; Solo se crea si ambos bloques están presentes. |
icon | .ant-notification-notice-icon | Icono decorativo. |
title | .ant-notification-notice-title | Encabezado. |
description | .ant-notification-notice-description | Descripción. |
actions | .ant-notification-notice-actions | Acciones directamente en la raíz del registro, junto al contenedor o texto. |
close | .ant-notification-notice-close | Botón de cierre. |
progress | .ant-notification-notice-progress | Banda de tiempo restante. |
Tokens de diseño
En el tema de ejemplo, el color de la banda establece progressBg. Haga clic en "Mostrar durante 2 segundos".
| Simbólico | Asignar |
|---|---|
width | Ancho de la tarjeta: Número en px o CSS Longitud; está limitado por la ventana gráfica. |
zIndexPopup | CSS Capa de grupo de ubicaciones; Popover nativo permanece en la capa top. |
progressBg | Tiempo restante de la banda de color. |
colorInfoBg | Registro explícito de información de fondo. |
colorSuccessBg | Registro de éxito de fondo explícito. |
colorWarningBg | Antecedentes del registro de advertencia explícito. |
colorErrorBg | Antecedentes explícitos de registro de errores. |
| Simbólico | Valor |
|---|---|
colorBgElevated | #ffffff |
colorText | rgba(0,0,0,0.88) |
colorTextHeading | rgba(0,0,0,0.88) |
colorSuccess | #52c41a |
colorError | #ff4d4f |
colorInfo | #1677ff |
colorWarning | #faad14 |
borderRadiusLG | 8 |
FAQ
¿Cómo obtener ConfigProvider contexto?
poner NotificationHolder de su createNotification dentro del proveedor. Una instancia necesita un titular.
¿Cuál es la diferencia entre notification del mensaje?
notification Diseñado para encabezado, detalles y acciones. Message da una respuesta corta.
¿Cómo actualizar una entrada existente?
Repita open con el mismo key y nuevos ajustes.
¿Cómo guardar la descripción de DOM al cambiar el estado?
Ajustar type ya al abrir. Agregar o eliminar un icono puede volver a crear un contenedor de texto.
¿Cuándo se detiene el temporizador?
Cuando flota con pauseOnHover y foco dentro actions. false/0 Deshabilitar el cierre automático.
¿Cómo cambiar el color de la banda de tiempo?
Establecer theme.components.Notification.progressBg y activar showProgress. En Ejemplo de tema haga clic en Mostrar durante 2 segundos.
¿Adónde fueron las notificaciones anteriores?
Mueva el enfoque a Apilar para abrir las tarjetas. Si se da Límite de cola, las entradas más antiguas se cierran cuando se agregan nuevas.
¿Necesito volver a crear la notificación después de cambiar el tema?
No. Fichas de diseño (tokens de diseño) se actualizan reactivamente, manteniendo la cola y el cronograma de cierre.
¿Por qué los fondos de estado son los mismos?
El valor predeterminado es colorBgElevated. Se pueden establecer diferentes fondos con tokens de componentes notification.
¿Cómo devolver el ancho estándar?
Eliminar override o pasar una configuración de componente vacío. Explícito width:undefined difiere del campo que falta.