ReactiveNative

React-native Loading图的正确加载

2017-04-11  本文已影响777人  随遇而安_2750
Loading图适用于网络图片加载失败或者加载过程中的占位图,以下先展示最简单的网络请求占位图:

请求的图片地址:

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

render方法:

render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          Loading图的模拟加载
        </Text>
        {this.renderLoadImg()}
        <Text style={styles.instructions}>
          1秒以后,会请求网络数据
        </Text>
      </View>
    );
  }

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

renderLoadImg(){
    let img;
    if(this.state.imgUrl){
      img = (<Image source={{uri:this.state.imgUrl}} style={{width:200,height:200}} />);
    }else{
      img = (<Image source={require('./img/loading.png')} style={{width:200,height:200}} />)
    }
    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 (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          Loading图的模拟加载
        </Text>
        {this.renderLoadImg()}
        <Text style={styles.instructions}>
          1秒以后,会请求网络数据
        </Text>
      </View>
    );
  }

  renderLoadImg(){
    let img;
    if(this.state.imgUrl){
      img = (<Image source={{uri:this.state.imgUrl}} style={{width:200,height:200}} />);
    }else{
      img = (<Image source={require('./img/loading.png')} style={{width:200,height:200}} />)
    }
    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);

效果如下:

示例效果
使RN支持gif图设置方法:

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

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

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

上一篇 下一篇

猜你喜欢

热点阅读