自定义react组件:Img,图片获取失败时能显示指定的默认图片

前端之家收集整理的这篇文章主要介绍了自定义react组件:Img,图片获取失败时能显示指定的默认图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

自定义react组件,Img,图片获取失败时能显示指定的默认图片

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. /**
  4. * 图片加载失败就显示默认图片
  5. */
  6. class Img extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = {
  10. imageUrl: this.props.imageUrl
  11. };
  12. }
  13.  
  14. handleImageLoaded() {
  15. }
  16.  
  17. handleImageErrored() {
  18. this.setState({
  19. imageUrl: this.props.defaultImg
  20. });
  21. }
  22.  
  23. render() {
  24. return (
  25. <img style={this.props.style}
  26. src={this.state.imageUrl}
  27. onLoad={this.handleImageLoaded.bind(this)}
  28. onError={this.handleImageErrored.bind(this)}
  29. />
  30. );
  31. }
  32. }
  33. export default Img;

猜你在找的React相关文章