1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
| import { useState, useRef, useEffect } from 'react';
const LazyImage = ({ src, alt, placeholder, className }) => {
const [isLoaded, setIsLoaded] = useState(false);
const [isInView, setIsInView] = useState(false);
const imgRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsInView(true);
observer.disconnect();
}
},
{ threshold: 0.1 }
);
if (imgRef.current) {
observer.observe(imgRef.current);
}
return () => observer.disconnect();
}, []);
const handleLoad = () => {
setIsLoaded(true);
};
return (
<div ref={imgRef} className={className}>
{isInView && (
<img
src={src}
alt={alt}
onLoad={handleLoad}
style={{
opacity: isLoaded ? 1 : 0,
transition: 'opacity 0.3s ease'
}}
/>
)}
{!isLoaded && (
<div
className="image-placeholder"
style={{
backgroundColor: '#f0f0f0',
backgroundImage: placeholder ? `url(${placeholder})` : 'none',
backgroundSize: 'cover',
backgroundPosition: 'center'
}}
/>
)}
</div>
);
};
// 响应式图片组件
const ResponsiveImage = ({ sources, alt, className }) => {
const [loadedSources, setLoadedSources] = useState(new Set());
const handleSourceLoad = (src) => {
setLoadedSources(prev => new Set(prev).add(src));
};
return (
<picture className={className}>
{sources.map(({ srcSet, media, type }) => (
<source
key={srcSet}
srcSet={srcSet}
media={media}
type={type}
onLoad={() => handleSourceLoad(srcSet)}
/>
))}
<img
src={sources[sources.length - 1].fallback}
alt={alt}
loading="lazy"
/>
</picture>
);
};
|