feat(ui): 增加头像组件错误处理功能

This commit is contained in:
zyh 2024-10-22 04:50:30 +00:00
parent e9ed7c924b
commit b3afb9c9d8

View File

@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
interface AvatarProps {
src: string;
@ -7,11 +7,21 @@ interface AvatarProps {
}
export function Avatar({ src, alt, className = '' }: AvatarProps) {
const [imgSrc, setImgSrc] = useState(src);
const [error, setError] = useState(false);
const handleError = () => {
setError(true);
// 设置一个默认的头像 URL
setImgSrc('/default-avatar.png');
};
return (
<img
src={src}
src={imgSrc}
alt={alt}
className={`w-8 h-8 rounded-full object-cover ${className}`}
className={`w-8 h-8 rounded-full object-cover ${className} ${error ? 'opacity-50' : ''}`}
onError={handleError}
/>
);
}