我正在开发反应原生的UI,在这个<Image>
与源一起使用,我想通过setNativeProps而不是通过状态更改图像源。
我的代码是:
<Image source={require('imagePath')} ref="icon"/>
在某些事件上我想改变它的来源:
this.refs['icon'].setNativeProps({
source: require('newImagePath')
});
但没有任何反应,它没有改变。通过使用NativeProps,图像的样式被更改,但像源和类似的道具不会改变。
那么请给我一个解决方案,如何通过使用其refs或key(而不是使用this.setState)更改任何特定事件的图像源
最后,我找到了通过静态图像更改图像源的方法。我们首先需要将resolveAssetSource函数用于静态图像,然后将其放在src中。
import resolveAssetSource from 'resolveAssetSource';
...
var imgsrc = require('imagePath');
this.refs['icon'].setNativeProps({
src: [resolveAssetSource(imgsrc)]
});
更新:
在IOS上,使用source而不是src。
感谢@DennisFrea给出了我想要的答案 - 只需将源添加为数组而不是对象。
正确的语法
this._imageContainer.setNativeProps({
source: [{ uri: newImageSource }]
})
语法不正确
this._imageContainer.setNativeProps({
source: { uri: newImageSource }
})
我认为这是不可能的,因为RN处理状态的方式和require()捆绑文件的方式。
但是,我可以想到两件事要尝试: