React中img图片加载完成前的loading效果
- 我在React中有这么一个需求,那就是我希望在图片加载完成前的时候一直显示loading动画效果,等图片加载完成了就实现图片的渲染
- 先讲讲具体的思路,再来说说实际的应用
- 实现思路:
var imglist = ['http://example.com/demo1.png','http://example.com/demo2.png','http://example.com/demo3.png']
var images = []
imglist.forEach(el=>{
var image = new Image()
image.src = el
image.onload = function(){
images.push(image)
}
})
if(images.length === 3){
}else{
}
import React from 'react'
import { Carousel, Spin } from 'antd'
class Home extends React.Component{
constructor(props){
super(props)
this.state = {
imglist: [
{
id: '01',
src: 'http://example.com/demo1.png',
alt: 'demo1'
},
{
id: '02',
src: 'http://example.com/demo2.png',
alt: 'demo2'
},
{
id: '03',
src: 'http://example.com/demo3.png',
alt: 'demo3'
}
],
images: []
}
}
UNSAFE_componentWillMount(){
var { imglist } = this.state
var images = []
imglist.forEach(el=>{
var image = new Image()
image.src = el.src
image.onload = ()=>{
images.push(image)
this.setState({
images
})
}
})
}
render(){
var { imglist, images } = this.state
if(images.length === 3){
return (
<div className='common-body'>
<Carousel autoplay>
{imglist.map(el=>(
<img src={el.src} key={el.id} alt={el.alt} />
))}
</Carousel>
</div>
)
}else{
return (
<div className='common-loading'>
<Spin tip='Loading...' size='large'></Spin>
</div>
)
}
}
}
export default Home