-
-
Notifications
You must be signed in to change notification settings - Fork 672
Description
I write a component `import React, { useEffect } from 'react';
import LazyLoad from 'vanilla-lazyload';
import classnames from 'classnames';
import './index.scss';
const classPrefix = 'qnr-img-lazy-load';
const placeholderImg = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAJCAYAAAA7KqwyAAAAAXNSR0IArs4c6QAAABZJREFUKFNjZKAQMFKon2HUAIbhEAYADbYACoSGQt8AAAAASUVORK5CYII=';
interface ImgLazyLoadProps {
/**
- @description 图片链接
/
src: string;
/* - @description 图片alt
/
alt?: string;
/* - @description 图片浮层内容
/
children?: React.ReactNode | React.ReactNode[];
/* - @description 样式
/
restStyles?: React.CSSProperties;
/* - @description 样式
/
className?: string;
/* - @description 是否开启懒加载
- @default true
/
isLazyLoad?: boolean;
/* - @description 只展示图片,没有占位图片
- @default false
*/
onlyImg?: boolean;
}
declare global {
interface Window {
lazyLoadInstance: any; // 懒加载实例
}
}
// Only initialize it one time for the entire application
if (typeof window !== 'undefined' && !window.lazyLoadInstance) {
window.lazyLoadInstance = new LazyLoad({
elements_selector: .${classPrefix}-lazy
,
});
}
const ImgLazyLoad = (props: ImgLazyLoadProps) => {
const { src, children, className, isLazyLoad = true, onlyImg = false, restStyles = {}, ...others } = props;
useEffect(() => {
if (window.lazyLoadInstance && typeof window.lazyLoadInstance.update === 'function') {
window.lazyLoadInstance.update();
}
}, [src]);
return (
<>
{onlyImg ? (
<img
className={classnames(
className,
isLazyLoad ? ${classPrefix}-lazy ${classPrefix}-lazy-img
: '',
)}
style={restStyles}
src={isLazyLoad ? placeholderImg : src}
data-src={isLazyLoad ? src : undefined}
alt='img'
{...others}
/>
)
: (
<div
className={classnames(
className,
isLazyLoad ? ${classPrefix}-lazy ${classPrefix}-lazy-bg
: '',
)}
style={restStyles}
data-bg={isLazyLoad ? src : undefined}
{...others}
>
{children}
)
}
</>
);
};
export default ImgLazyLoad;
`
index.css
`$class-prefix-img-lazy-load: 'qnr-img-lazy-load';
.#{$class-prefix-img-lazy-load} {
&-lazy-img {
width: 100%; /* 根据屏幕宽度设置图片宽度 /
height: 100%; / 高度自适应 */
background-color: rgba(0, 0, 0, .1);
}
&-lazy-img.loaded {
background-color: transparent; /* 图片加载完成后移除占位图 */
}
&-lazy-bg {
position: relative;
width: 100%;
height: 100%;
min-height: 100%;
background: rgba(0, 0, 0, .1)
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAJCAYAAAA7KqwyAAAAAXNSR0IArs4c6QAAABZJREFUKFNjZKAQMFKon2HUAIbhEAYADbYACoSGQt8AAAAASUVORK5CYII=') center center / cover no-repeat;
}
}
`
when i use this in nextjs。it happen wrong.
the same img ,Repeat the request once
How can I solve this?