Skip to content

how to use in nextjs #621

@xiaomuzizier

Description

@xiaomuzizier

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 {
/**

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.

in server
image
the img is lost .

in client
image

the same img ,Repeat the request once

How can I solve this?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions