简体   繁体   English

在React native中运行时加载图像

[英]Loading image at runtime in React native

There are many such situation in my app where I need to set image at run time. 在我的应用程序中有很多这样的情况,我需要在运行时设置图像。 for example 例如

1. I get the Image URL on button click 1.点击按钮获取图片网址

2. I need to display image (loader) on button click 2.我需要在按钮点击时显示图像(加载器)

3. I need to change image depending upon the user's action 3.我需要根据用户的动作改变图像

How do I do this? 我该怎么做呢? So far I am not able to figure out how to access my nodes (let it be Text, Image, Text Input etc) 到目前为止,我无法弄清楚如何访问我的节点(让它成为文本,图像, 文本输入等)

For showing loader image i found many packages, but i don't want to use a package just for showing a loader image. 为了显示加载器图像我发现了很多包,但我不想仅仅为了显示加载器图像而使用包。

Any code concept or tutorial will be Appreciated. 任何代码概念或教程都将得到赞赏。

Update: I am setting image in constructor (this is static image) class LoginScreen extends Component { 更新:我在构造函数中设置图像(这是静态图像)类LoginScreen扩展Component {

constructor(props){
      super(props);
      this.setState({imageUri:'../images/loader.gif'});
}

In render method i'm using image tag like this render方法中,我使用像这样的图像标签

<Image source={{uri: this.state.imageUri}} style={styles.image}  />

It is throwing null error on the image tag error: "null is not an object(evlauating this.state.imageUri). 它在图像标记错误上抛出空错误:“null不是对象(evlauating this.state.imageUri)。

Where Am i mistaking? 我错在哪里? Also i need to set this image on button click. 此外,我需要在按钮单击设置此图像。 Before that it should be hidden. 在此之前它应该被隐藏。 How to implement these scenarios? 如何实施这些方案?

All of these cases can be resolved by using a component's state to store the image URLs. 所有这些情况都可以通过使用组件的状态来存储图像URL来解决。 For instance: 例如:

<Image source={{uri: this.state.imageUri}} />

In your render method, followed by: 在您的渲染方法中,后跟:

this.setState({
  imageUri: // Some uri...
})

Would allow you to have a dynamic image based on both user events, and runtime variables. 允许您根据用户事件和运行时变量获得动态图像。

For showing a loading state while the image downloads I'd recommend the react-native-image-progress component which handles the display of a loading indicator while the image downloads. 为了在图像下载时显示加载状态,我建议使用react-native-image-progress组件,该组件在图像下载时处理加载指示器的显示。

Using a number of simple components like this is completely normal when developing React Native apps, so don't be overly-concerned about utilising 3rd-party code like that. 在开发React Native应用程序时,使用像这样的一些简单组件是完全正常的,所以不要过分担心使用这样的第三方代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM