image - 如何在组件加载时对数组中的所有项目使用 Image.getSize?
问题描述
我正在尝试全宽(并按比例)显示图像,因此我需要获取高度来确定纵横比,然后确定图像数组的新高度。Image.getSize 似乎是获取宽度和高度的最佳方法,但我似乎无法想出一种安全有效的方法来获取所有尺寸。
在下面的代码中, postImages 获取一个图像 url 数组,然后我运行 useEffect 来检查它是否存在,然后循环遍历该数组。
我关心的是如何有效地获取高度和宽度。目前这需要很长时间,并且在控制台中我可以无限期地看到 console.log (“这继续在下面重复运行”)。
有没有更好的方法来使用这个 Image.getSize 函数?我不应该在 useEffect 中使用它吗?有没有更好的方法来更新这组图像的宽度和高度?
export default posts = (props) => {
let { post } = props
let { postImages = [] } = post
const [images, setImages] = useState([])
useEffect(() => {
let images = []
if(postImages){
postImages.map((img) => {
Image.getSize(
img,
(width, height) => {
console.log("this continues to run repeatedly")
setImages([...images, { url: img, width, height }])
}
);
}, [postImages]);
}
})
先感谢您!
解决方案
你需要useState
吗useEffect
?据我从问题中了解到,您想获得一组图像,其大小取决于道具,那么是否需要存储它们?
export default posts = (props) => {
let { post } = props
let { postImages = [] } = post
const images = []
if(postImages) {
postImages.map((img) => ({
Image.getSize(
img, (width, height) => {
console.log("this continues to run repeatedly on props change")
s.push({ url: img, width, height })
})
})
}
}
推荐阅读
- c++ - 为什么我的项目设置在发布模式下会发生冲突?
- javascript - 两个 React 组件中的电子处理事件
- magento2 - Magento 2 // 在类别页面上显示“优惠标签” // Amasty 特别促销
- c# - Blazor onchange 段落
- sockets - 为什么 TCP Socket send() 给出失败的错误代码 58?
- javascript - 如何在没有按钮的情况下检查单选框情况?
- java - 尝试使用滑块在画布上绘图
- python - 在python3 json中按值查找键
- https - 如何使用 Fiddler 将 Rest API 请求从开发服务器重定向到 localhost
- java - 从html java读取时保留特殊字符?