简体   繁体   中英

Return a value to caller function

I need to set the image URI on a state value previewImage but the problem is that the value is inside a function. I need to get the image URI from inside the function and return it back to the caller function to save it on the state.

This is the called component

const ImageDisplay = (images, onPress) => {
    
return (
  {images.map((image, index) => (
    <TouchableOpacity onPress={onPress(image)}>
      <Image source={{uri: image}} />
    </TouchableOpacity> 
  ))}
);

This the component that calls the above

<ImageDisplay images={images} onPress={viewImage} />

And this is what is done on the value that it got from inside the component

const viewImage = (uri) => {
  setPreviewImage(uri);
  console.log(uri)
}

The problem is the value I see on the console is not the URI of the image but a bunch of data which is Class {...}

How can I get the image URI from inside the component then return it back to the caller component?

You are calling onPress instead of passing it as a function. You want:

    images.map(image => (
       <TouchableOpacity onPress={() => onPress(image)}>
            <Image source={{uri: image}} />
       </TouchableOpacity> 
    )

This assumes images is an array of strings.

You should declare a function, by your code in first render it will run:

const ImageDisplay = (images, onPress) => {
  const pressHandler = () => onPress(image);
    
  return (
    <>
      {images.map((image, index) => (
        <TouchableOpacity onPress={pressHandler}>
          <Image source={{uri: image}} />
        </TouchableOpacity> 
      ))}
    </>
  );
};

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