前端如果一次請求的頁面上有過多的圖片,可能因為圖片過多而網(wǎng)速過慢等原因,不能一次加載出來儡羔,為此占位符是必須添加的。
這時就可以自己簡單寫個組件璧诵,來實現(xiàn)懶加載笔链,我們現(xiàn)在模擬個接口。模擬加載的端口一共有十個 JSON 信息腮猖,我們只需要根據(jù)提供的圖片地址來加載圖片鉴扫。
所以整體的思路就是:
- 根據(jù)請求來加載圖片
- 使用自定義組件把圖片地址下傳
- 子組件創(chuàng)建虛擬的 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(){
// 創(chuàng)建一個虛擬圖片
const img = new Image();
// 發(fā)出請求坪创,請求圖片
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= "此處是經(jīng)過 base64 轉碼的loading圖鏈接"/>
}
</div>
)
}
}
把網(wǎng)速調慢實現(xiàn)結果:
loading 占位圖.gif