简体   繁体   中英

how do I access the values from getSize function in react native

I've written this code within a.map method to get the size of the image if an image exists, but I can't figure out a way to actually use the values 'width' and 'height'. When I console.log imageDimensions, it returns undefined

let imageDimensions
if(item.imageRoutes.length > 0){
  Image.getSize(item.imageRoutes[0].fileLink, (width, height) => {
    imageDimensions = ([width, height])
  })
  console.log(index, imageDimensions)
}

Image.getSize returns its values asynchronously. So, you get width and height in the callback function where you set imageDimensions . If you wanted to log it, you'd have to move that code:

let imageDimensions
if(item.imageRoutes.length > 0){
  Image.getSize(item.imageRoutes[0].fileLink, (width, height) => {
    imageDimensions = {width, height};
    console.log(index, imageDimensions); //here
  })
}

In terms of actually using those values in react, you'll probably want to use a state variable for them. If you're using function components, for example, you'd want to do your Image.getSize call in a useEffect and then store the value using useState

Update based on comment: Storing multiple image sizes in useState :

const [imageSizes, setImageSizes] = useState({})

//inside your useEffect, when you get a new image size (assuming width and height were returned from getSize and imageUri holds the URI to the image:

//then to check it later
const imageSize = imageSizes[imageUri]
setImageSizes(prevState => {...prevState, [imageUri]: {width, height}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM