如何在 react native 中使用 setNativeProps 更改图像的来源 [英] How to change the source of image by using setNativeProps in react native
问题描述
我正在用 React Native 开发 UI,在这个
与源一起使用,我想通过 setNativeProps 而不是状态来更改图像源.
I am developing UI in react native, In this <Image>
is used with source and i wanted to change the image source by setNativeProps not by state.
我的代码是:
<Image source={require('imagePath')} ref="icon"/>
在某些事件上,我想更改其来源:
On certain Event i want to change its source:
this.refs['icon'].setNativeProps({
source: require('newImagePath')
});
但是什么都没有发生,它没有改变.通过使用 NativeProps 改变了图像的风格,但像 source 之类的 props 没有改变.
But nothing happens, its not change. By using NativeProps the style of image is changed but the props like source and like that not changes.
所以请给我一个解决方案,如何通过使用其引用或键(而不是使用 this.setState)来更改任何特定事件的图像源
So please give me a solution that how can i change the source of image on any certain event by using its refs or key (not by using this.setState)
推荐答案
我终于找到了可以通过静态图像更改图像源的方法.我们首先需要对静态图片使用resolveAssetSource函数,然后放到src中.
Finally I found the way you can change the image source by static image. We first need to use resolveAssetSource function to the static image and then put it in src.
import resolveAssetSource from 'resolveAssetSource';
...
var imgsrc = require('imagePath');
this.refs['icon'].setNativeProps({
src: [resolveAssetSource(imgsrc)]
});
更新:
在 IOS 上,使用 source 而不是 src.
On IOS, use source instead of src.
这篇关于如何在 react native 中使用 setNativeProps 更改图像的来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!