The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

70 lines
1.3 KiB

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. class ImageLoader extends React.PureComponent {
  4. static propTypes = {
  5. alt: PropTypes.string,
  6. src: PropTypes.string.isRequired,
  7. previewSrc: PropTypes.string.isRequired,
  8. width: PropTypes.number.isRequired,
  9. height: PropTypes.number.isRequired,
  10. }
  11. static defaultProps = {
  12. alt: '',
  13. };
  14. state = {
  15. loading: true,
  16. error: false,
  17. }
  18. componentWillMount() {
  19. this._loadImage(this.props.src);
  20. }
  21. componentWillReceiveProps(props) {
  22. this._loadImage(props.src);
  23. }
  24. _loadImage(src) {
  25. const image = new Image();
  26. image.onerror = () => this.setState({ loading: false, error: true });
  27. image.onload = () => this.setState({ loading: false, error: false });
  28. image.src = src;
  29. this.setState({ loading: true });
  30. }
  31. render() {
  32. const { alt, src, previewSrc, width, height } = this.props;
  33. const { loading } = this.state;
  34. return (
  35. <div className='image-loader'>
  36. <img
  37. alt={alt}
  38. className='image-loader__img'
  39. src={src}
  40. width={width}
  41. height={height}
  42. />
  43. {loading &&
  44. <img
  45. alt=''
  46. src={previewSrc}
  47. className='image-loader__preview-img'
  48. />
  49. }
  50. </div>
  51. );
  52. }
  53. }
  54. export default ImageLoader;