"use client" import { useState, useRef, useEffect } from "react" import Image from "next/image" import { useDeviceInfo } from "@/hooks/use-mobile" interface OptimizedImageProps { src: string alt: string width?: number height?: number className?: string priority?: boolean onClick?: () => void onLoad?: () => void } export function OptimizedImage({ src, alt, width, height, className = "", priority = false, onClick, onLoad }: OptimizedImageProps) { const [isLoaded, setIsLoaded] = useState(false) const [isInView, setIsInView] = useState(false) const [hasError, setHasError] = useState(false) const imgRef = useRef(null) const { isMobile, viewport } = useDeviceInfo() // 交叉观察器用于懒加载 useEffect(() => { if (priority) { setIsInView(true) return } const observer = new IntersectionObserver( ([entry]) => { if (entry.isIntersecting) { setIsInView(true) observer.disconnect() } }, { rootMargin: isMobile ? "50px" : "100px", // 移动端更小的预加载距离 threshold: 0.1 } ) if (imgRef.current) { observer.observe(imgRef.current) } return () => observer.disconnect() }, [priority, isMobile]) const handleLoad = () => { setIsLoaded(true) onLoad?.() } const handleError = () => { setHasError(true) } // 根据设备选择合适的图片质量 const getOptimizedSrc = (originalSrc: string) => { if (hasError) return "/placeholder.svg" // 如果是移动端,可以考虑使用更低质量的图片 if (isMobile && viewport.width < 768) { // 这里可以添加图片质量优化逻辑 // 例如:添加 ?quality=80&w=400 等参数 return originalSrc } return originalSrc } return (
{/* 骨架屏加载状态 */} {!isLoaded && isInView && (
)} {/* 错误状态 */} {hasError && (

图片加载失败

)} {/* 实际图片 */} {isInView && !hasError && ( {alt} )} {/* 渐进式加载效果 */} {isLoaded && (
)}
) }