[英]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.