Next.js 图像组件 props onLoadingComplete 不起作用?

问题描述 投票:0回答:2

我试图从 onLoadingComplete 属性中获取 naturalWidthnaturalHeighthttps://nextjs.org/docs/api-reference/next/image#onloadingcomplete 但它不起作用?也许我做错了?

我有这个功能:

const handleImageLoad = (e) => {
  console.log("load", e);
};

然后我从 next.js 得到这个组件

<Image
  onLoadingComplete={(e) => handleImageLoad(e)}
  className=""
  src={image["data_url"]}
  alt=""
  layout="fill"
  objectFit="contain"
/>

加载图像时,它不会执行任何操作,如果我尝试控制台日志,它会起作用,但我不知道为什么当我传递

handleImageLoad

时它不起作用
onLoadingComplete={() => handleImageLoad()}
reactjs next.js react-props nextjs-image
2个回答
4
投票

编辑:在 v11.1.3-canary.33 中修复


如果提供

next/image
是数据 URI,则
onLoadingComplete
组件似乎不会调用
src
处理程序。 (我可以看到您已经在here为此打开了一个问题。)

目前的解决方法是使用对象 URL。如果您愿意,您可以直接实现它。请参阅此线程或链接的问题。

如果你想继续使用

react-images-uploading
,你可以使用这个线程和其他人中提到的方法,将提供的数据URI转换为对象URL,然后将其作为
src
传递给
next/image
。显然,与自己处理上传的文件相比,这将是性能消耗更大的操作。

这是一个工作示例:https://codesandbox.io/s/jolly-ellis-4htdl?file=/pages/index.js

为了完整起见,只是添加一个替代方案:

import { useState } from "react";
import Image from "next/image";

const IndexPage = () => {
  const [src, setSrc] = useState("");

  const handleChange = (e) => {
    setSrc(URL.createObjectURL(e.target.files[0]));
    return true;
  };

  const handleImageLoad = (e) => {
    console.log("load", e);
  };

  return (
    <>
      <input
        type="file"
        id="foo"
        name="foo"
        accept="image/png, image/jpeg"
        onChange={handleChange}
      />
      <div
        style={{
          marginTop: "1rem",
          width: 600,
          height: 600,
          backgroundColor: "blue",
          position: "relative"
        }}
      >
        {src?.length > 0 && (
          <Image
            onLoadingComplete={(e) => {
              handleImageLoad(e);
            }}
            src={src}
            alt=""
            layout="fill"
            objectFit="contain"
          />
        )}
      </div>
    </>
  );
};

export default IndexPage;

0
投票

我遇到了类似的错误,我试图使图像仅在加载时才可见。

事实证明,如果您将样式设置为

display:none
则不会调用
onLoadingComplete
,如下所示:

<Image

    ...

    style={{
        display: "none"
    }}

    onLoadingComplete={(img) => { // this will not be invoked
        img.style.opacity = "block"
    }}
/>

为了解决这个问题,我必须设置不同的样式定义一个空的

onError
函数(没有它,无论图像源有效还是无效,即损坏的图像,都会调用
onLoadingComplete

<Image

    ...

    style={{
        visibility: "hidden",
        maxHeight: "0",
        maxWidth: "0"
    }}

    onLoadingComplete={(img) => {
        img.style.visibility = "visible"
        img.style.maxHeight = "none"
        img.style.maxWidth = "none"
    }}

    onError={() => {}}
/>

这是针对 Next.js -v13.5.3 进行测试的

© www.soinside.com 2019 - 2024. All rights reserved.