自动安装
npx tofu-ui-cli@latest add avatar
手动安装 (可选)
注意
如果你使用手动安装,将无法获取更新
在项目目录中创建如下路径文件:
components/ui/tofu/avatar.tsx然后复制此代码:
import React, { FC } from 'react';
/**
* TofuUI Avatar 头像
* @author shuakami
* @version 1.0.0
* @copyright ByteFreeze&TofuUI
*/
interface AvatarProps {
imageUrl?: string;
alt?: string;
initials?: string;
backgroundColor?: string;
size: 'xs' | 'sm' | 'md' | 'xl' | '2xl' | '3xl';
}
const sizeMap = {
xs: 24,
sm: 34,
md: 48,
xl: 64,
'2xl': 80,
'3xl': 96
};
const Avatar: FC<AvatarProps> = ({ imageUrl, alt, initials, backgroundColor = 'bg-gray-200', size }) => {
const pixelSize = sizeMap[size];
const hasImage = Boolean(imageUrl);
const style = {
width: `${pixelSize}px`,
height: `${pixelSize}px`,
backgroundColor: hasImage ? undefined : backgroundColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '50%',
};
return (
<div style={style} className="overflow-hidden relative flex h-10 w-10 shrink-0 rounded-full">
{hasImage ? (
<img src={imageUrl} alt={alt || 'Avatar'} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<span className="text-white" style={{ fontSize: `${pixelSize / 2.5}px` }}>
{initials}
</span>
)}
</div>
);
};
export default Avatar;导入组件
import Avatar from '@/components/ui/tofu/avatar';使用组件
你可以这样使用Avatar组件来显示一个图片头像:
<Avatar
imageUrl="https://example.com/avatar.jpg"
alt="您的头像描述"
size="md" // 可为 "xs", "sm", "md", "xl", "2xl", "3xl"
/>或者,如果你想显示一个字母头像,可以这样:
<Avatar
initials="JT"
backgroundColor="#4CAF50"
size="sm"
/>示例
JT
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| imageUrl | string | undefined | 头像图片的URL,如果提供了URL,将显示图片,否则显示初始化文字 |
| alt | string | undefined | 图片描述,用于无障碍访问 |
| initials | string | undefined | 没有图片时显示的初始化文字 |
| backgroundColor | string | 'bg-gray-200' | 没有图片时的背景颜色 |
| size | 'xs' | 'sm' | 'md' | 'xl' | '2xl' | '3xl' | 必需 | 头像的大小,支持多种预设尺寸 |