ReactJS 图片加载监控与 Skeleton 占位符实现
在 React 中,我们可以使用<img>标签来展示图片。要实现监控图片加载进程和展示skeleton的效果,可以使用以下步骤:
- 创建一个状态变量
isLoading,初始值为true,表示图片还在加载中。 - 在
<img>标签中添加onLoad和onError事件监听器,分别对应图片加载成功和失败的情况。 - 在
onLoad事件处理函数中,将isLoading状态变量设置为false,表示图片加载完成。 - 在
render()方法中,根据isLoading状态变量的值展示skeleton或图片。
以下是实现这个功能的代码示例:
import React, { useState } from 'react';
function ImageWithLoader(props) {
const [isLoading, setIsLoading] = useState(true);
function handleImageLoaded() {
setIsLoading(false);
}
function handleImageError() {
setIsLoading(false);
}
return (
<div>
{isLoading && <div className='skeleton'></div>}
<img src={props.src} onLoad={handleImageLoaded} onError={handleImageError} style={{ display: isLoading ? 'none' : 'block' }} />
</div>
);
}
在上面的代码中,我们使用了一个skeleton div来代替图片加载中的效果。当isLoading状态为true时,展示skeleton,否则展示图片。在handleImageLoaded和handleImageError事件处理函数中,我们将isLoading状态变量设置为false,表示图片加载完成。
使用这个组件时,只需要传入图片的URL即可:
<ImageWithLoader src='https://example.com/image.jpg' />
原文地址: https://www.cveoy.top/t/topic/oA1y 著作权归作者所有。请勿转载和采集!