[英]How to run a function onLoad of an image in NextJS Image component
我想在加載圖像時顯示骨架。 我試圖在 NextJS 提供的新Image
組件中傳遞onLoad
道具,但 function 在加載圖像之前觸發。
這是我的代碼
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 現在提供了一個placeholer和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
一個回調 function 在圖像完全加載並且占位符已被刪除后調用。
https://nextjs.org/docs/api-reference/next/image#onloadingcomplete
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.