[英]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
.所以我现在在 Google 和 Stackoverflow 中查找了大约一个 hout,但我找不到解决我的问题的方法:我有一个带有存储在 var
like_uri
中的内部源的图像。 Now the image displays fine and it works.现在图像显示正常并且可以正常工作。 I wrapped it with a
<TouchableOpacity>
including a onPress()
.我用包括
onPress()
的<TouchableOpacity>
包裹它。 Everytime the user clicks this image, it should update it self by updating the source-variable like_uri
.每次用户点击这张图片时,它都应该通过更新源变量
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?
因此,如果 A 处于活动状态并按下它应该显示 B,如果 B 处于活动状态并按下它应该显示 A。任何解决方法或解决方案?
You have to put your URI
in the state and update the state on your onPress
您必须将您的
URI
放入 state 并在您的onPress
上更新 state
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.设置一个值不会更好地重新渲染组件,使用 state 并在图像之间切换,如下所示。
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>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.