2017-06-01 01:07:25 +10:00
|
|
|
import React from 'react';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
|
|
|
|
class ImageLoader extends React.PureComponent {
|
|
|
|
|
|
|
|
static propTypes = {
|
2017-06-15 22:10:41 +10:00
|
|
|
alt: PropTypes.string,
|
2017-06-01 01:07:25 +10:00
|
|
|
src: PropTypes.string.isRequired,
|
2017-06-07 03:30:17 +10:00
|
|
|
previewSrc: PropTypes.string.isRequired,
|
|
|
|
width: PropTypes.number.isRequired,
|
|
|
|
height: PropTypes.number.isRequired,
|
2017-06-01 01:07:25 +10:00
|
|
|
}
|
|
|
|
|
2017-06-15 22:10:41 +10:00
|
|
|
static defaultProps = {
|
|
|
|
alt: '',
|
|
|
|
};
|
|
|
|
|
2017-06-01 01:07:25 +10:00
|
|
|
state = {
|
|
|
|
loading: true,
|
|
|
|
error: false,
|
|
|
|
}
|
|
|
|
|
|
|
|
componentWillMount() {
|
2017-06-07 03:30:17 +10:00
|
|
|
this._loadImage(this.props.src);
|
2017-06-01 01:07:25 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
componentWillReceiveProps(props) {
|
2017-06-07 03:30:17 +10:00
|
|
|
this._loadImage(props.src);
|
2017-06-01 01:07:25 +10:00
|
|
|
}
|
|
|
|
|
2017-06-07 03:30:17 +10:00
|
|
|
_loadImage(src) {
|
2017-06-01 01:07:25 +10:00
|
|
|
const image = new Image();
|
2017-06-07 03:30:17 +10:00
|
|
|
|
2017-06-02 01:25:10 +10:00
|
|
|
image.onerror = () => this.setState({ loading: false, error: true });
|
2017-06-07 03:30:17 +10:00
|
|
|
image.onload = () => this.setState({ loading: false, error: false });
|
|
|
|
|
2017-06-01 01:07:25 +10:00
|
|
|
image.src = src;
|
2017-06-07 03:30:17 +10:00
|
|
|
|
2017-06-02 01:25:10 +10:00
|
|
|
this.setState({ loading: true });
|
2017-06-01 01:07:25 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
2017-06-15 22:10:41 +10:00
|
|
|
const { alt, src, previewSrc, width, height } = this.props;
|
2017-06-24 00:05:04 +10:00
|
|
|
const { loading } = this.state;
|
2017-06-01 01:07:25 +10:00
|
|
|
|
2017-06-07 03:30:17 +10:00
|
|
|
return (
|
|
|
|
<div className='image-loader'>
|
2017-06-15 22:10:41 +10:00
|
|
|
<img
|
|
|
|
alt={alt}
|
2017-06-07 03:30:17 +10:00
|
|
|
className='image-loader__img'
|
|
|
|
src={src}
|
|
|
|
width={width}
|
|
|
|
height={height}
|
|
|
|
/>
|
|
|
|
|
|
|
|
{loading &&
|
2017-06-15 22:10:41 +10:00
|
|
|
<img
|
|
|
|
alt=''
|
2017-06-07 03:30:17 +10:00
|
|
|
src={previewSrc}
|
|
|
|
className='image-loader__preview-img'
|
|
|
|
/>
|
|
|
|
}
|
|
|
|
</div>
|
|
|
|
);
|
2017-06-01 01:07:25 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default ImageLoader;
|