react懒加载如何放默认图
实现React懒加载时设置默认图的方法
在React中实现懒加载(Lazy Loading)时,可以通过以下方式设置默认占位图,优化用户体验并避免布局偏移。
使用loading属性与onError事件
对于原生<img>标签,可直接通过loading="lazy"启用懒加载,并配合onError事件回退到默认图:

<img
src="实际图片URL"
loading="lazy"
onError={(e) => {
e.target.src = "默认图URL";
e.target.onerror = null; // 防止循环报错
}}
alt="描述文字"
/>
结合Intersection Observer自定义懒加载
通过Intersection Observer API监听元素可见性,动态加载图片:

import { useRef, useEffect, useState } from 'react';
function LazyImage({ src, alt, placeholder }) {
const imgRef = useRef();
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && !isLoaded) {
const img = new Image();
img.src = src;
img.onload = () => setIsLoaded(true);
img.onerror = () => setIsLoaded(false); // 加载失败保持占位图
observer.unobserve(entry.target);
}
});
});
if (imgRef.current) observer.observe(imgRef.current);
return () => observer.disconnect();
}, [src, isLoaded]);
return (
<img
ref={imgRef}
src={isLoaded ? src : placeholder}
alt={alt}
onError={(e) => {
e.target.src = placeholder;
e.target.onerror = null;
}}
/>
);
}
使用第三方库(如react-lazy-load-image-component)
通过库提供的<LazyLoadImage>组件快速实现:
import { LazyLoadImage } from 'react-lazy-load-image-component';
import 'react-lazy-load-image-component/src/effects/blur.css';
function MyComponent() {
return (
<LazyLoadImage
src="实际图片URL"
placeholderSrc="默认图URL"
effect="blur" // 可选模糊过渡效果
onError={(e) => {
e.target.src = "默认图URL";
}}
/>
);
}
CSS背景图懒加载方案
对于CSS背景图,可通过动态类名控制:
function LazyDiv({ imageUrl, placeholder }) {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const img = new Image();
img.src = imageUrl;
img.onload = () => setLoaded(true);
img.onerror = () => setLoaded(false);
}, [imageUrl]);
return (
<div
className={`lazy-bg ${loaded ? 'loaded' : ''}`}
style={{
backgroundImage: loaded ? `url(${imageUrl})` : `url(${placeholder})`
}}
/>
);
}
关键注意事项
- 错误处理:始终为
onError事件添加处理逻辑,避免因图片加载失败导致空白。 - 性能优化:压缩默认图体积,建议使用Base64内联小图(<2KB)。
- SEO友好:确保默认图的
alt属性描述准确,不影响无障碍访问。 - 布局稳定:为懒加载容器设置固定宽高或比例,防止内容跳动。






