首页 > 解决方案 > 如何在组件加载时对数组中的所有项目使用 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]);
    }
  })
  

先感谢您!

标签: imagereact-nativereact-hooksuse-effect

解决方案


你需要useStateuseEffect?据我从问题中了解到,您想获得一组图像,其大小取决于道具,那么是否需要存储它们?

  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 })
                })
        })
      }
  }

推荐阅读