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

Next.js Image component props onLoadingComplete not working?

我正在尝试从 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()}

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


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

目前的解决方法是使用 Object URLs. If you wish, you can implement this quite directly. Refer this thread 或链接的问题。

如果您想继续使用react-images-uploading,您可以使用this thread和其他方法中提到的方法,将提供的数据URI转换为对象URL,然后将其作为srcnext/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;