如何在NextJS image组件中运行onLoad函数



我想在加载图像时显示骨架。我试图在NextJS提供的新Image组件中传递onLoadprop,但该函数在加载图像之前触发。

我的代码

const [loaded, setLoaded] = useState(false);
<Image
src={src}
alt={""}
className={styles.image_tag}
onLoad={(e) => setLoaded(true)}
style={{ opacity: loaded ? "1" : "0" }}
layout={"fill"}
/>
{!loaded && (
<Skeleton
className={styles.skeleton}
variant={"rect"}
animation={"wave"}
/>
)}

你可以像这样使用onLoad道具:

引用自https://github.com/vercel/next.js/discussions/20155

const [isImageReady, setIsImageReady] = useState(false);
const onLoadCallBack = (e)=>{
setIsImageReady(true)
typeof onLoad === "function" && onLoad(e)
}
return(
<div>
{!isImageReady && 'loading image...'}
<Image 
onLoad={onLoadCallBack} 
src={'/'+image} 
alt={title} 
width={260}  
height={160} />
</div>
)

*******************************<更新>*****************************

Nextjs现在提供了占位符blurDataURL用于在加载主图像之前显示图像占位符的道具。

一个例子

<Image
className="image"
src={image.src}
alt={image.alt}
layout="fill"
objectFit="cover"
objectPosition="top center"
placeholder="blur"
blurDataURL="/images/blur.jpg"
/>

从11.1开始,您可以使用onLoadingComplete

当图像完成后调用的回调函数已加载,占位符已被删除。

https://nextjs.org/docs/api-reference/next/image onloadingcomplete

最新更新