React loading 占位图

前端如果一次请求的页面上有过多的图片,可能因为图片过多而网速过慢等原因,不能一次加载出来,为此占位符是必须添加的。

这时就可以自己简单写个组件,来实现懒加载,我们现在模拟个接口。模拟加载的端口一共有十个 JSON 信息,我们只需要根据提供的图片地址来加载图片。

所以整体的思路就是:

  • 根据请求来加载图片
  • 使用自定义组件把图片地址下传
  • 子组件创建虚拟的 image 标签,检测图片是否加载完成来显示 loading 图或真正的图片。

请求图片和图片下传:

import React, { Component } from 'react';
import axios from "axios";
import "../css/css.css";
import LazyLd from "./LazyLd";

export default class App extends Component {
    constructor(){
        super();
        this.state = {
            res : []
        }
    }
    componentWillMount(){
        axios.get("http://192.168.2.250/car").then(data=>{
            this.setState({
                res : data.data.results
            })
        })
    }
    render() {
        return (
            <div>
                <ul className = "cur" id="images">
                {
                    this.state.res.map((item,index) => <li key = {index}><LazyLd width = {150} height = {100}  src={`http://192.168.2.250/images/carimages_small/${item.id}/view/${item.image}`}></LazyLd></li>)
                }
                </ul>
            </div>
        )
    }
}

懒加载组件:

import React, { Component } from 'react'

export default class LazyLd extends Component {
    constructor(){
        super();
        this.state = {
            done : false
        }
    }
    componentWillMount(){
        // 创建一个虚拟图片
        const img = new Image();
        // 发出请求,请求图片
        img.src = this.props.src;
        // 当图片加载完毕
        img.onload = () => {
            this.setState({
               done : true
            });
        }
    }
    render() {
        return (
            <div>
                 {
                        this.state.done
                        ?
                        <img style={{
                            'width': this.props.width + 'px',
                            'height': this.props.height + 'px'
                        }} src={this.props.src} />
                        :
                        <img style={{
                            'width': this.props.width + 'px',
                            'height': this.props.height + 'px'
                        }} src= "此处是经过 base64 转码的loading图链接"/>
                }
            </div>
        )
    }
}

把网速调慢实现结果:


loading 占位图.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 隔阂说来就来 连声招呼都不打 由喜欢到讨厌 就在 那么一瞬间
    如果行文可以不按逻辑阅读 148评论 0 0
  • 【在爱中行走】 趁着今天在招募在爱中行走第十一季的义工,小新今天想跟大家聊聊在爱中行走这个项目。 2013年1月1...
    我的小千世界阅读 1,558评论 0 0
  • 敬爱的李老师,智慧的班主任,亲爱的跃友们: 大家好!我是来自青岛西海岸新区直路房产的薛萍 今天是我的日精进行动第...
    薛艳萍阅读 144评论 0 1
  • 在朱克曼家的谷仓里,快乐地生活着一群动物,其中小猪威尔伯和蜘蛛夏洛建立了最挚的友谊。然而,一个最丑恶的消息打破了谷...
    丹dan1234阅读 123评论 0 0
  • 我什么都没有了, 亲情像童年一样远去了, 友谊在匆忙里逐渐褪色, 学业无成自信荡然无存, 珍视的爱让我委屈丛生。 ...
    达安一阅读 499评论 2 1

友情链接更多精彩内容