Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在react native中使用setNativeProps更改图像源_Javascript_React Native - Fatal编程技术网

Javascript 如何在react native中使用setNativeProps更改图像源

Javascript 如何在react native中使用setNativeProps更改图像源,javascript,react-native,Javascript,React Native,我正在react native中开发UI,在这篇文章中,与源代码一起使用,我想通过setNativeProps而不是状态来更改图像源代码 我的代码是: <Image source={require('imagePath')} ref="icon"/> 但是什么都没有发生,它没有改变。 通过使用NativeProps,图像的样式会发生变化,但像source之类的道具不会发生变化 因此,请给我一个解决方案,如何通过使用某个事件的refs或key(而不是使用this.setState)来

我正在react native中开发UI,在这篇文章中,
与源代码一起使用,我想通过setNativeProps而不是状态来更改图像源代码

我的代码是:

<Image source={require('imagePath')} ref="icon"/>
但是什么都没有发生,它没有改变。 通过使用NativeProps,图像的样式会发生变化,但像source之类的道具不会发生变化


因此,请给我一个解决方案,如何通过使用某个事件的refs或key(而不是使用this.setState)来更改该事件的图像源。

最后,我找到了通过静态图像更改图像源的方法。我们首先需要对静态映像使用resolveAssetSource函数,然后将其放入src中

import resolveAssetSource from 'resolveAssetSource';

...


var imgsrc = require('imagePath');

this.refs['icon'].setNativeProps({
   src: [resolveAssetSource(imgsrc)]
});
更新:


在IOS上,使用source而不是src。

我认为这是不可能的,因为RN处理状态的方式和require()绑定文件的方式

然而,我可以想到两件事来尝试:

  • ForceUpdate:尝试在本机道具之后调用this.refs['icon'].ForceUpdate(),以强制重新渲染
  • 在图像中设置一个包装并更新该包装,这样就不会修改原始图像源
    类似这样:

    感谢@DennisFrea,他给出了我想要的答案——只需将源添加为数组而不是对象

    正确语法

    this._imageContainer.setNativeProps({
      source: [{ uri: newImageSource }]
    })
    
    this._imageContainer.setNativeProps({
      source: { uri: newImageSource }
    })
    
    语法错误

    this._imageContainer.setNativeProps({
      source: [{ uri: newImageSource }]
    })
    
    this._imageContainer.setNativeProps({
      source: { uri: newImageSource }
    })
    

    同样的问题谢谢Dennis的帮助,但是我想用这个来改变静态图像。我已经编辑了我的答案,请看上面的,已经测试并在这里工作了。src在android平台上工作正常,但在iOS上不工作。因此,我们没有使用src,而是使用了在iOS上正常工作的source。感谢sachin的反馈。我会更新答案。顺便说一句,我在android上尝试使用“源代码”但不工作Getting error
    无法读取未定义的属性“setNativeProps”
    V0.56