React实现下拉刷新、图片懒加载、上滑加载更多、图片预加载
1.首先在componentDidMount钩子函数中,调用接口,之后CarList渲染到页面
async componentDidMount() {
this.CarArray = await searchCar({
page: 1, mod: "宝马" });
this.setState({
CarList: this.CarArray
})
this.ScrollHeight = this.refs.loadMore.scrollHeight;
this.EveryHeight = this.ScrollHeight / this.CarArray.length;
this.ViewHeight = document.documentElement.clientHeight;
this.FnSetHeight();
for (let i = 0; i < this.ImageList.length; i++) {
let URL = this.ImageList[i];
let Images = new Image();
Images.src = URL;
Images.onload = function () {
this.ImagLoad++;
if (this.ImagLoad >= this.ImageList.length) {
this.setState({
CarList: this.CarArray,
loadingState: 0,
})
}
}.bind(this)
document.onscroll = this.FnDelayedLoad.bind(this);
}
}
2.将设置图片的高的代码进行封装,以便于下一次调用
FnSetHeight() {
for (let i = 0; i < this.CarArray.length; i++) {
let Car = this.CarArray[i];
Car.heights = this.EveryHeight * i;
if (this.ViewHeight >= Car.heights) {
Car.imageState = 1
this.ImageList.push(`http://www.ibugthree.com/${
Car.img_src}`);
} else {
Car.imageState = 0
}
}
}
3.这里的imageState其实是根据不同的情况来显示
ImageState(item) {
if (item.imageState) {
return `http://www.ibugthree.com/${
item.img_src}`;
} else {
return `http://www.ibugthree.com/default.gif`;
}
}
4.最后的话添加它的上滑加载更多
async FnDelayedLoad() {