react实现img的onerror

前端之家收集整理的这篇文章主要介绍了react实现img的onerror前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. import React from 'react';
  2. import {Link} from 'react-router';
  3. import ContactStore from '../stores/ContactStore'
  4. import ContactActions from '../actions/ContactActions';
  5.  
  6. class Contact extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.state = ContactStore.getState();
  10. this.onChange = this.onChange.bind(this);
  11. }
  12.  
  13. componentDidMount() {
  14. ContactStore.listen(this.onChange);
  15. ContactActions.getContact(this.props.params.id);
  16. }
  17.  
  18. componentWillUnmount() {
  19. ContactStore.unlisten(this.onChange);
  20. }
  21.  
  22. componentDidUpdate(prevProps) {
  23. if (prevProps.params.id !== this.props.params.id) {
  24. ContactActions.getContact(this.props.params.id);
  25. }
  26. }
  27.  
  28. onChange(state) {
  29. this.setState(state);
  30. }
  31.  
  32. onError() {
  33. this.setState({
  34. imageUrl: "img/default.png"
  35. })
  36. }
  37.  
  38. render() {
  39. return (
  40. <div className='container'>
  41. <div className='list-group'>
  42. <div className='list-group-item animated fadeIn'>
  43. <h4>{this.state.contact.displayname}</h4>
  44. <img onError={this.onError.bind(this)} src={this.state.imageUrl} />
  45. </div>
  46. </div>
  47. </div>
  48. );
  49. }
  50.  
  51. export default Contact;

猜你在找的React相关文章