图片加载效果
完整代码
import { useRef, useState } from 'react';
import './index.less';
export default function Img(props) {
const {
style = {},
src = "",
alt = "",
errImg = "",
loadingImg = `https://img1.baidu.com/it/u=2097753014,2835891615&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281`
} = props;
const imgRef = useRef<HTMLDivElement>(null);
const [error, setError] = useState(false);
const [neededSrc, setNeededSrc] = useState(loadingImg || src);
const [random, setRandom] = useState<number>();
// 加载失败
const onError = (obj: any) => {
if (imgRef?.current?.className) {
imgRef.current.className = 'hiddleImg'
}
setError(true);
}
const onLoad = (url: string) => {
setError(false);
// 创建一个img标签
const imgDom = new Image();
imgDom.src = url;
imgDom.onload = function () {
console.log('onload--');
setNeededSrc(url);
}
imgDom.onerror = () => {
onError({});
};
}
// 重新加载
const reLoad = () => {
console.log('重新加载');
setError(false);
setRandom(Date.now());//通过改改url地址重新渲染
}
// 加载失败返回渲染
if (error) {
return (
<div style={style}>
<div className='img-error-tip' style={style}>
HELLE ERROR
<span className='reload-text' onClick={() => reLoad()}>Reload</span>
</div>
</div>
)
}
// 加载成功返回渲染
return (
<div ref={imgRef} className="img">
<img
style={style}
src={`${neededSrc}?${random}`}
alt={alt}
onLoad={() => onLoad(props?.src)}
onError={() => onError({ url: errImg })}
/>
</div>
)
}
.hiddleImg {
display: none;
}
.img-error-tip {
text-align: center;
display: table-cell;
vertical-align: middle;
border: 1px #888 solid;
.reload-text {
cursor: pointer;
color: #861354;
padding-left: 4px;
font-weight: bold;
}
}
组件使用
import Image from '@/components/Image';
{
list?.map(v => {
return (
<div key={v} className="note-book_img">
<Image
src={v}
alt={""}
style={{ height: 200, width: 400, marginLeft: 20 }}
/>
</div>
)
})
}