Avatar 頭像
頭像元件,支援圖片、圖示、文字三種內容;圖片為空或載入失敗時依次自動回退。
基礎用法
基礎用法
水水水水水
import { LhAvatar } from '@lh-ui/react'
export default function Demo() {
return (
<>
<LhAvatar src="/avatars/ink.png" />
<LhAvatar src="/avatars/ink.png" shape="square" />
<LhAvatar text="水墨" />
<LhAvatar icon="user" />
</>
)
}
Avatar Props
| 屬性 | 說明 | 類型 | 可選值 | 預設值 |
|---|---|---|---|---|
| src | 圖片地址;為空時依次回退到圖示、文字、自訂內容 | string | — | — |
| alt | 圖片載入失敗的替代文字,同時作為圖示/文字分支的無障礙名稱 | string | — | — |
| icon | 圖示回退:字串取內建 LhIcon 圖示名,也可傳任意 ReactNode 自訂圖示 | ReactNode | — | — |
| text | 文字頭像內容(src 與 icon 都缺省時取首字展示) | string | — | — |
| shape | 頭像形狀 | 'circle' | 'square' | — | 'circle' |
| size | 頭像大小 | 'mini' | 'small' | 'medium' | 'large' | 'x-large' | — | 'medium' |
| fit | 圖片填充模式 | 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | — | 'cover' |
| sx | 快速佈局屬性 | SxProps | — | — |
Avatar 事件
| 事件 | 說明 | 回呼簽名 | Vue 對照 |
|---|---|---|---|
| onError | 圖片載入失敗時觸發 | (event: SyntheticEvent<HTMLImageElement>) => void | @error |
回退順序
內容按 src 圖片 → icon 圖示 → text 首字 → children 依次回退:src 為空或圖片載入失敗時走圖示分支,都沒有才取 text 首字。文字頭像取第一個字元(按碼點提取,emoji 亦適用),如「水墨」→「水」、「Alice 」→「A」。
與 Vue 版的對應
src / alt / text / shape / size / fit / sx 與 lh-ui-plus 的
LhAvatar 同名同義;React 無插槽,plus 的 #icon 與 icon prop 合併為一個 ReactNode prop(字串按內建圖示名解析),#default 兜底插槽映射為 children。
無障礙
圖片分支由 <img alt> 自身命名(未傳時依次取 alt / text / 'avatar');圖示與文字分支輸出 role="img",無障礙名稱取 alt——請為非圖片頭像傳入有語義的 alt。
樣式
import '@lh-ui/react/style/avatar'