Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to use in nextjs #621

Open
xiaomuzizier opened this issue Aug 5, 2024 · 0 comments
Open

how to use in nextjs #621

xiaomuzizier opened this issue Aug 5, 2024 · 0 comments

Comments

@xiaomuzizier
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant