Next.js图像组件道具onLoadingComplete不起作用? [英] Next.js Image component props onLoadingComplete not working?
本文介绍了Next.js图像组件道具onLoadingComplete不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从onLoadingComplete道具:https://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。如果您愿意,您可以非常直接地实现这一点。请参阅this thread或链接的问题。
如果您想继续使用react-images-uploading
,可以使用this thread等方法,将提供的数据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;
这篇关于Next.js图像组件道具onLoadingComplete不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文