闭社主体 forked from https://github.com/tootsuite/mastodon
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.

62 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. src: PropTypes.string.isRequired,
  6. previewSrc: PropTypes.string.isRequired,
  7. width: PropTypes.number.isRequired,
  8. height: PropTypes.number.isRequired,
  9. }
  10. state = {
  11. loading: true,
  12. error: false,
  13. }
  14. componentWillMount() {
  15. this._loadImage(this.props.src);
  16. }
  17. componentWillReceiveProps(props) {
  18. this._loadImage(props.src);
  19. }
  20. _loadImage(src) {
  21. const image = new Image();
  22. image.onerror = () => this.setState({ loading: false, error: true });
  23. image.onload = () => this.setState({ loading: false, error: false });
  24. image.src = src;
  25. this.setState({ loading: true });
  26. }
  27. render() {
  28. const { src, previewSrc, width, height } = this.props;
  29. const { loading, error } = this.state;
  30. return (
  31. <div className='image-loader'>
  32. <img // eslint-disable-line jsx-a11y/img-has-alt
  33. className='image-loader__img'
  34. src={src}
  35. width={width}
  36. height={height}
  37. />
  38. {loading &&
  39. <img // eslint-disable-line jsx-a11y/img-has-alt
  40. src={previewSrc}
  41. className='image-loader__preview-img'
  42. />
  43. }
  44. </div>
  45. );
  46. }
  47. }
  48. export default ImageLoader;