rn react-native-image-lazy-loading

npm install react-native-image-lazy-loading -S

import React from 'react';

import { Dimensions, InteractionManager, StyleSheet, Text, View, Image } from 'react-native';

import ImageLazy from 'react-native-image-lazy-loading';

const screenWidth = Dimensions.get('window').width;

const screenHeight = Dimensions.get('window').height;

export default class ImageLazyLoading extends React.PureComponent {

  constructor(props) {

    super(props);

    // 先给图片一个默认宽高

    this.state = {

      width: screenWidth,

      height: 300,

      loaded: false,

    };

    this._onLayout = this._onLayout.bind(this);

  }

  // 2、获取组件初始化位置

  _onLayout(e, node) {

    let { y } = e.nativeEvent.layout;

    this.setState({

      offsetY: y,

    });

  }

  // 获取加载中、加载失败视图的函数

  _renderLoad(text) {

    return (

      <View style={styles.loadContainer} onLayout={this._onLayout}>

        <Text style={styles.loadText}>{text}</Text>

      </View>

    );

  }

  // 从网络请求图片的方法

  _fetchImg() {

    InteractionManager.runAfterInteractions(() => {

      const { source, style } = this.props;

      if (source.uri) {

        // 如果是网络图片 在页面还未加载前,获取图片宽高

        Image.getSize(

          source.uri,

          (w, h) => {

            console.log('wwwww', w, h);

            let imgHeight = (h / w) * this.state.width;

            this.setState({

              height: imgHeight,

              loaded: true,

            });

          },

          (err) => {

            // 获取图片宽高或者下载图片失败

            this.setState({

              loadFail: true,

            });

          },

        );

      }

    });

  }

  render() {

    const { source, y } = this.props;

    // 3、判断是否可以加载图片了

    console.log(y, screenHeight, this.state.offsetY, this.state.loaded);

    if (y + screenHeight >= this.state.offsetY && !this.state.loaded) {

      // 请求图片

      this._fetchImg();

    }

    // 4、如果加载了远程图片,就会渲染这里

    if (this.state.loaded) {

      // 如果真正的图片加载好

      return <ImageLazy source={source} style={{ height: this.state.height }} resizeMode={'contain'} />;

    }

    // 1、会先显示加载中视图

    return this._renderLoad('正在加载中...');

  }

}

const styles = StyleSheet.create({

  // 加载容器样式

  loadContainer: {

    backgroundColor: '#eee',

    justifyContent: 'center',

    alignItems: 'center',

    height: 100,

    marginVertical: 10,

  },

  // 加载样式

  loadText: {

    fontSize: 20,

    color: '#ccc',

  },

});

-----------------------------------------------

<ImageLazyLoading source={item.imgSrcUrl ? { uri: item.imgSrcUrl } : {}} style={[styles.picSrc]} />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值