考虑以下组件
import React from 'react';
function Image() {
function onLoad() {
console.log("Loaded...")
}
return (
<img
src="http://..."
onLoad={onLoad}
decoding="async"
/>
);
}
export default Image;
由于某种原因,
onLoad
事件没有一致触发,即当我最初加载页面并刷新它时,它不会被触发,但是当我在反应中交互安装组件时,即没有页面加载时,它会被触发。
我尝试删除
decoding="async"
并添加 onError
处理程序以查看这些处理程序是否提供了更多信息,但行为没有改变。
我在 macOS safari 和 Chrome 浏览器上看到了同样的行为。
编辑:如果它不起作用,图像根本不会加载
我想出了如何让它在我的案例中发挥作用。我猜 onLoad 事件没有执行,因为图像已经加载,所以我将代码更改为以下内容,现在它按预期工作
import React, { useRef, useEffect } from 'react';
function Image() {
const imgRef = useRef<HTMLImageElement>(null);
function onLoad() {
console.log("Loaded...")
}
useEffect(() => {
if (imgRef.current?.complete) {
onLoad();
}
}, []);
return (
<img
ref={imgRef}
src="http://..."
onLoad={onLoad}
decoding="async"
/>
);
}
export default Image;
您能否提供有关该错误的更多信息? 它应该可以工作,使用箭头函数并在 img 的 onLoad 事件上调用它
import React from 'react';
onLoadFunction=()=>{
console.log('just loaded');
}
return (
<img
src="http://..."
onLoad={this.onLoadFunction}
/>
);
}
export default Image;
问题可能是
Image
是 DOM 中的保留键盘,请考虑更改函数的名称。否则可能会改变图像类别。
// Image Size is >3MB
const App = () => {
const onImageLoad = () => {
console.log("Working...")
}
return (
<div>
<img src="https://unplash-api.herokuapp.com/api/Ri8c2qFg32A/full" onLoad={onImageLoad}/>
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"))
img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
原因是因为图像甚至在 React 水化页面并开始侦听图像的
load
事件之前就已加载。可以在此 GitHub 问题上找到更深入的解释。
为了解决这个问题,@ilja 的解决方案通过
.complete
中的 useEffect
属性检查图像是否已加载,效果很好。