【问题标题】:How to run a function onLoad of an image in NextJS Image component如何在 NextJS Image 组件中运行图像的 onLoad 函数
【发布时间】:2021-04-25 00:05:32
【问题描述】:

我想在加载图像时显示骨架。我尝试在 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"}
  />
)}

【问题讨论】:

  • 只有在加载为真时才应该显示图像。它始终显示在您的代码中
  • 有什么方法可以优化 标签中的图片

标签: reactjs image next.js nextjs-image


【解决方案1】:

你可以像这样使用 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"
/>

【讨论】:

    【解决方案2】:

    从 11.1 开始,您可以使用 onLoadingComplete

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

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

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      相关资源
      最近更新 更多