Saltar al contenido principal

Resumen

Avatar muestra una imagen con una alternativa de primera letra. Úselo junto al nombre de un registro o dentro de un Chip. Su raíz predeterminada es un span de presentación.

”Uso”

Cuando la imagen no está presente o no se puede cargar, la alternativa muestra en mayúscula la primera letra del nombre sin espacios al inicio ni al final. Un nombre vacío muestra -. colorSeed elige colores de alternativa estables y su valor predeterminado es name; use un identificador de registro para mantener el color estable cuando cambie el nombre. La imagen y el respaldo predeterminado son decorativos. name proporciona la inicial visual y los colores de respaldo sin añadir una etiqueta accesible. Cuando el avatar es la única representación de una persona o un registro, establece imageProps={{ alt: name }} para etiquetar tanto la imagen como el respaldo predeterminado. Mantén el avatar como decorativo cuando un nombre visible o un propietario etiquetado ya proporcionen esa información. imageProps acepta el contrato completo de imagen, incluidos srcSet, sizes, crossOrigin, referrerPolicy, eventos nativos, refs y render. Su src anula la abreviatura src. fallbackProps acepta el contrato completo de respaldo, incluidos delay, elementos secundarios, etiquetado, refs y render. Un render de respaldo personalizado gestiona su semántica de accesibilidad; establece explícitamente aria-hidden cuando sea decorativo.

Compón las partes

Usa Avatar.Root, Avatar.Image y Avatar.Fallback cuando controles la anatomía. Root proporciona el tamaño, la forma y la apariencia del respaldo; no genera elementos secundarios ni etiquetas accesibles.
Las partes comparten el estado de carga de imágenes de Base UI. Image procesa un img después de una carga correcta de forma predeterminada, y Fallback procesa un span mientras la imagen está ausente, cargándose o ha fallado. delay pospone la visualización inicial del respaldo en milisegundos y su valor predeterminado es 0. Una fuente modificada se vuelve a cargar y puede reemplazar la imagen actual o el respaldo. Avatar.Image expone onLoadingStatusChange con los valores de estado idle, loading, loaded y error. La devolución de llamada se ejecuta cuando Base UI informa de un cambio de estado distinto de inactivo; desmontar la parte Image restablece el estado raíz compartido a idle. Root, Image y Fallback aceptan funciones de className, style y render que reconocen el estado con imageLoadingStatus; Image también expone transitionStatus. Usa keepMounted en Image cuando la imagen procesada deba cargarse en su lugar, incluido loading="lazy" o un componente de imagen optimizado. Reenvía los atributos nativos, los eventos y la ref desde procesadores de imágenes personalizados. Una imagen montada aún puede estar cargándose o haber fallado; inspecciona el estado de carga en lugar de considerar su presencia como un éxito. El procesador del componente frontal actualmente admite la ruta de precarga predeterminada con src. Su imagen host no recibe srcSet, sizes, loading, decoding ni referrerPolicy. Una función render personalizada cambiante con keepMounted puede dejar oculta una imagen decodificada porque el trabajador no puede leer su estado de finalización ni sus dimensiones. Usa allí la precarga predeterminada hasta que esas capacidades del procesador estén disponibles. Los tipos públicos AvatarRootProps, AvatarImageProps, AvatarFallbackProps, AvatarRootState, AvatarImageState, AvatarFallbackState y AvatarImageLoadingStatus se exportan desde twenty-ui/primitives/data-display. Las refs se dirigen al elemento DOM procesado: span, img y span de forma predeterminada, o al elemento proporcionado mediante render.

Forma y apariencia

shape acepta square, rounded-square o circle. Los tamaños son xs (12px), sm (14px), md (16px), lg (24px), xl (32px) y xxl (40px). Tanto xl como xxl usan texto alternativo de 16px. El anterior tamaño xl de 40px ahora es xxl. Actualiza los usos existentes de size="xl" a size="xxl" cuando deban seguir siendo de 40px. variant="outline" añade un borde a la alternativa. Las anulaciones de color, backgroundColor y borderColor personalizan la alternativa, mientras que una imagen cargada mantiene su apariencia original.
Un icon tiene prioridad sobre la imagen y la alternativa de primera letra. El icono en sí es decorativo, así que etiqueta la raíz cuando transmita información. pulsing anima la opacidad y respeta las preferencias de movimiento reducido.

Abrir un perfil

Compón un botón nativo para las acciones. Gestiona el foco, la activación con Intro y Espacio, y el comportamiento deshabilitado. Proporciona un nombre accesible específico para la acción. Coloca onClick y disabled en el botón procesado; el Avatar abreviado no tiene la prop onClick, disabled ni nativeButton. Para la navegación, compón un ancla con un href o un enlace de enrutador que preserve la semántica de ancla. Los enlaces nativos se activan con Intro. Mantén la navegación y el comportamiento deshabilitado con el enlace o componente interactivo que compongas.

Migra los avatares en los que se puede hacer clic

Compón un botón nativo mediante render para las acciones, o un ancla o enlace de enrutador para la navegación. Mueve onClick y disabled a ese propietario y elimina nativeButton. Proporciona al propietario un nombre accesible útil y evita anidar elementos interactivos. Avatar.Root y las demás partes explícitas conservan el contrato completo de eventos de Base UI. Los avatares abreviados son decorativos de forma predeterminada. name no da nombre a la imagen, al respaldo ni al propietario interactivo. Usa un imageProps.alt no vacío solo cuando el avatar transmita una identidad que no esté ya proporcionada por texto visible o una etiqueta del propietario. Con partes explícitas, proporciona tú mismo el texto alternativo de la imagen y las etiquetas de respaldo o los atributos decorativos, y conserva el contenido traducido en tu aplicación.

”Props”

Los tipos y valores predeterminados se generan a partir de los tipos de componentes públicos. Las partes explícitas aceptan atributos nativos y controladores de eventos. El Avatar abreviado omite onClick; proporciónalo en el propietario pasado mediante render.
string
Background color override for a first-letter fallback.
string
Border color override for the outline fallback.
string | ((state: AvatarRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
string
Text color override for a first-letter fallback.
string
Stable value used to choose fallback colors. Defaults to name.
AvatarFallbackProps
Complete Avatar.Fallback props, including caller-owned children, labeling, refs, render, and fallback delay in milliseconds.
ReactNode
Decorative icon rendered instead of the image and first-letter fallback. Give the root an accessible label when the icon conveys information.
AvatarImageProps
Complete Avatar.Image props, including native image attributes, refs, render, keepMounted, and onLoadingStatusChange. Alternative text defaults to an empty string. Supply a nonempty alt to label the image and default fallback.
string
Name used for the first-letter fallback and fallback colors. Does not add an accessible label.
boolean
predeterminado:"false"
Animates the avatar opacity. Respects reduced-motion preferences.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AvatarRootState>
Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.
boolean
predeterminado:"false"
Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct.
"circle" | "rounded-square" | "square"
predeterminado:"square"
Shape of the avatar and its fallback.
"lg" | "md" | "sm" | "xl" | "xs" | "xxl"
predeterminado:"md"
Avatar size: xs (12px), sm (14px), md (16px), lg (24px), xl (32px), or xxl (40px).
string | null
Image URL. A missing or failed image shows the fallback. imageProps.src overrides this value.
CSSProperties | ((state: AvatarRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
"outline" | "soft"
predeterminado:"soft"
Visual treatment of the fallback.

Avatar.Root

string
Background color override for a first-letter fallback.
string
Border color override for the outline fallback.
ReactNode
Caller-owned Image, Fallback, and other content.
string | ((state: AvatarRootState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
string
Text color override for a first-letter fallback.
string
Stable value used to choose fallback colors. Defaults to name.
string
Name used to choose fallback colors. Does not add children or accessible labels.
boolean
predeterminado:"false"
Animates the avatar opacity. Respects reduced-motion preferences.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AvatarRootState>
Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.
boolean
predeterminado:"false"
Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct.
"circle" | "rounded-square" | "square"
predeterminado:"square"
Shape of the avatar and its fallback.
"lg" | "md" | "sm" | "xl" | "xs" | "xxl"
predeterminado:"md"
Avatar size: xs (12px), sm (14px), md (16px), lg (24px), xl (32px), or xxl (40px).
CSSProperties | ((state: AvatarRootState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.
"outline" | "soft"
predeterminado:"soft"
Visual treatment of the fallback.

Avatar.Image

string
Caller-owned alternative text. Use an empty string for decorative images.
string | ((state: AvatarImageState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
"" | "anonymous" | "use-credentials"
Native image cross-origin policy, also used during preloading.
boolean
predeterminado:"false"
Keeps the image mounted and loads it in place. Loading and failed images stay hidden while Fallback is shown.
"eager" | "lazy"
Native eager or lazy loading. Use keepMounted for lazy loading.
((status: ImageLoadingStatus) => void)
Called when Base UI reports a loading, loaded, or error status. Shares that state with Root and Fallback.
"" | "no-referrer-when-downgrade" | "no-referrer" | "origin-when-cross-origin" | "origin" | "same-origin" | "strict-origin-when-cross-origin" | "strict-origin" | "unsafe-url"
Native image referrer policy, also used during preloading.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, AvatarImageState>
Replaces the image. Preserve a native image and forward the supplied attributes, events, and ref.
string
Native responsive image sizes used with srcSet.
string
Image URL. Image renders after a successful load unless keepMounted is enabled.
string
Native responsive image source candidates.
CSSProperties | ((state: AvatarImageState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.

Avatar.Fallback

ReactNode
Caller-owned fallback content, such as initials or an icon.
string | ((state: AvatarFallbackState) => string | undefined)
CSS class applied to the element, or a function that returns a class based on the component’s state.
number
predeterminado:"0"
Milliseconds before the initial fallback is shown. Defaults to 0.
ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AvatarFallbackState>
Replaces the fallback span. Forward the supplied props and ref, and provide its accessible label or decorative attributes.
CSSProperties | ((state: AvatarFallbackState) => CSSProperties | undefined)
Style applied to the element, or a function that returns a style object based on the component’s state.