如何 运行 NextJS 图像组件中图像的函数 onLoad

How to run a function onLoad of an image in NextJS Image component

我想在加载图像时显示骨架。我试图在 NextJS 提供的新 Image 组件中传递一个 onLoad 属性,但该函数在加载图像之前就被触发了。

这是我的代码

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 现在提供 placeholerblurDataURL 道具,您可以使用它们在加载主图像之前显示图像占位符。

一个例子


<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

A callback function that is invoked once the image is completely loaded and the placeholder has been removed.

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