'use client'; import { useState, useCallback } from 'react'; import Image from 'next/image'; import { cn } from '@/lib/utils'; interface OptimizedImageProps { src: string; alt: string; width?: number; height?: number; fill?: boolean; className?: string; containerClassName?: string; priority?: boolean; sizes?: string; quality?: number; placeholder?: 'blur' | 'empty'; blurDataURL?: string; } export function OptimizedImage({ src, alt, width, height, fill = false, className, containerClassName, priority = false, sizes = '(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw', quality = 85, placeholder = 'blur', blurDataURL, }: OptimizedImageProps) { const [isLoaded, setIsLoaded] = useState(false); const [error, setError] = useState(false); // 生成默认的模糊占位符 const defaultBlurDataURL = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MDAiIGhlaWdodD0iNDAwIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjFmNWY5Ii8+PC9zdmc+'; // 使用 callback 来处理加载状态 const handleLoad = useCallback(() => { setIsLoaded(true); }, []); const handleError = useCallback(() => { setError(true); }, []); if (error) { return (
图片加载失败
); } return (
{/* 模糊占位符背景 */} {!isLoaded && placeholder === 'blur' && (
)} {/* 加载动画 */} {!isLoaded && (
)} {alt}
); }