React-native Loading图的正确加载

Loading图适用于网络图片加载失败或者加载过程中的占位图,以下先展示最简单的网络请求占位图:

请求的图片地址:

const URL = 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1333472173,1434096058&fm=80&w=179&h=119&img.JPEG';

render方法:

render() {
    return (
      
        
          Welcome to React Native!
        
        
          Loading图的模拟加载
        
        {this.renderLoadImg()}
        
          1秒以后,会请求网络数据
        
      
    );
  }

renderLoadImg方法的解释:
当网络数据加载完成后,显示所加载的图片;没有加载完成的时候,显示Loading图。

renderLoadImg(){
    let img;
    if(this.state.imgUrl){
      img = ();
    }else{
      img = ()
    }
    return img;
}

模拟漫长的网络请求过程:用到了setTimeout方法,模拟1s后请求成功。

componentDidMount(){
    setTimeout(()=>{
      this.setState({
        imgUrl:URL
      })
    },1000)
} 
完整代码如下:
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

const URL = 'https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1333472173,1434096058&fm=80&w=179&h=119&img.JPEG';


export default class imgRes extends Component {

  constructor(props){
    super(props);
    this.state = {
      imgUrl:null
    }
  }

  componentDidMount(){
    setTimeout(()=>{
      this.setState({
        imgUrl:URL
      })
    },1000)
    
  } 

  render() {
    return (
      
        
          Welcome to React Native!
        
        
          Loading图的模拟加载
        
        {this.renderLoadImg()}
        
          1秒以后,会请求网络数据
        
      
    );
  }

  renderLoadImg(){
    let img;
    if(this.state.imgUrl){
      img = ();
    }else{
      img = ()
    }
    return img;
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('imgRes', () => imgRes);

效果如下:

React-native Loading图的正确加载_第1张图片
示例效果
使RN支持gif图设置方法:

在android\build.gradle中dependencies依赖中添加如下代码:

compile 'com.facebook.fresco:animated-gif:0.13.0'

这样就可以引用gif图片了。。。。

你可能感兴趣的:(React-native Loading图的正确加载)