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

hel*_*llo 2 reactjs next.js react-props nextjs-image

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

我有这个功能:

const handleImageLoad = (e) => {
  console.log("load", e);
};
Run Code Online (Sandbox Code Playgroud)

然后我有来自 next.js 的这个组件

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

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

onLoadingComplete={() => handleImageLoad()}
Run Code Online (Sandbox Code Playgroud)

brc*_*-dd 5

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


如果提供的是数据 URI,该next/image组件似乎不会调用处理程序。(我可以看到你已经在这里打开了一个相同的问题。)onLoadingCompletesrc

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

如果您想继续使用,您可以使用本线程react-images-uploading和其他线程中提到的方法,将提供的数据 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;
Run Code Online (Sandbox Code Playgroud)