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