简体   繁体   中英

Updating an Image in React Native on press

So I looked in Google and Stackoverflow for about an hout now, but I can't find the solution to my problem: I have an Image with a inter source which is stored in the var like_uri . Now the image displays fine and it works. I wrapped it with a <TouchableOpacity> including a onPress() . Everytime the user clicks this image, it should update it self by updating the source-variable like_uri . My idea looks like following:

 var like_uri = require('../pictures/sections/hearth_empty.png'); const pressLike = () => { like_uri = require('../pictures/sections/hearth_full.png'); }... <TouchableOpacity onPress={pressLike}> <Image source={like_uri} style={{height: 28, width: 28, marginTop: 4}}></Image> </TouchableOpacity>

I get no error code or something, but it simply does not do anything. Already checked the source etc. and they are good. Somehow it wont update my picture. Also would like to switch between these two pictures. So if A is active and pressed it should display B and if B is active and pressed it should display A. Any work arounds or solutions?

You have to put your URI in the state and update the state on your onPress

const [like_uri, setUri]:  useState(require('../pictures/sections/hearth_empty.png')); // Initial state

 const pressLike = () => {
 setUri(require('../pictures/sections/hearth_full.png'));
}

<TouchableOpacity onPress={()=>pressLike()}>
  <Image source={like_uri} style={{height: 28, width: 28, marginTop: 4}}></Image>
</TouchableOpacity>

Setting a value wont re render the component better use a state and switch between your images, something like below.

const SwitchImage = () => {
  const [pressed, setPressed] = useState(false);
  const like_uri1 = require('../pictures/sections/hearth_empty.png');
  const like_uri12 = require('../pictures/sections/hearth_full.png');

  const pressLike = () => {
    setPressed(!pressed);
  };

  return (
    <TouchableOpacity onPress={pressLike}>
      <Image
        source={pressed ? like_uri1 : like_uri12}
        style={{ height: 28, width: 28, marginTop: 4 }}
      />
    </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