我有一個帶有鏈接的物件
const urls = {
small: https://image1.com,
medium: https://image2.com,
large: https://image3.com,
};
輸出應如下所示:
{
small: {width: image_width, height: image_height},
medium: {width: image_width, height: image_height},
large: {width: image_width, height: image_height}
}
我試過這樣,但結果是一個無限回圈。幫助我修復我的功能或以另一種方式展示它是如何實作的
const [imageSize, setImageSize] = useState({});
const getImageSize = () => {
for (const url in urls) {
const img = new Image();
img.src = urls[url];
img.onload = () => {
setImageSize((prev) => {
return {
...prev,
[url]: {
width: img.width,
height: img.height,
},
};
});
};
}
};
uj5u.com熱心網友回復:
要觸發影像onload偵聽器,它應該被安裝到 DOM,否則你setImageSize不會被呼叫。為此,您應該有有效的影像并將其附加到 html 的某個位置,如下所示:
const urls = {
small: 'https://dummyimage.com/600x400/000/fff',
medium: 'https://dummyimage.com/600x400/000/fff',
large: 'https://dummyimage.com/600x400/000/fff',
}
const getImageSize = () => {
for (const url in urls) {
const img = new Image()
img.src = urls[url]
img.onload = () => {
setImageSize(prev => {
return {
...prev,
[url]: {
width: img.width,
height: img.height,
},
}
})
}
document.body.appendChild(img)
}
}
useEffect(() => {
getImageSize()
}, [])
uj5u.com熱心網友回復:
試試下面的代碼:
const [imageSize, setImageSize] = useState({});
const urls = {
small: https://image1.com,
medium: https://image2.com,
large: https://image3.com,
};
const getImageSize = () => {
for (const size in urls) {
var img = new Image();
img.onload = function() {
setImageSize((prev) => {
return {
...prev,
[size]: {width: this.width, height: this.height}
}
})
};
img.src = url;
}
}
useEffect(() => {
getImageSize()
}, [])
uj5u.com熱心網友回復:
檢查小提琴鏈接我希望它會作業[https://jsfiddle.net/k7bue0ho/][1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/476634.html
標籤:javascript 反应
