javascript - react.js 替换 img src onerror

标签 javascript reactjs http-status-code-404

我有一个 React 组件,它是列表中的详细 View 。

如果图像不存在并且出现 404 错误,我将尝试用默认图像替换该图像。

我通常会在 img 标签中使用 onerror 方法,但这似乎不起作用。

我不确定如何用 React 做到这一点。

这是我的组件:

import React from 'react';
import {Link} from 'react-router';
import ContactStore from '../stores/ContactStore'
import ContactActions from '../actions/ContactActions';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = ContactStore.getState();
    this.onChange = this.onChange.bind(this); 
 }

componentDidMount() {
  ContactStore.listen(this.onChange);
  ContactActions.getContact(this.props.params.id);
}

componentWillUnmount() {
  ContactStore.unlisten(this.onChange);
}

componentDidUpdate(prevProps) {
  if (prevProps.params.id !== this.props.params.id) {
    ContactActions.getContact(this.props.params.id);
  }
}

onChange(state) {
  this.setState(state);
}

render() {
  return (
    <div className='container'>
      <div className='list-group'>
        <div className='list-group-item animated fadeIn'>
          <h4>{this.state.contact.displayname}</h4>
          <img src={this.state.imageUrl} />
        </div>
      </div>
    </div>
  );
}
}

export default Contact;

最佳答案

这最适合我

<img 
  src={record.picture}
  onError={({ currentTarget }) => {
    currentTarget.onerror = null; // prevents looping
    currentTarget.src="image_path_here";
  }}
/>

关于javascript - react.js 替换 img src onerror,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097560/

相关文章:

javascript - 使用 jQuery/Ajax 从数据库中检索记录

javascript - 防止 NodeJS 在开发/调试时缩小 JavaScript 代码

javascript - 无论单击“确定”还是“取消”,我的确认弹出窗口仍在删除对象。为什么? Angular 怪?

javascript - 用 'recompose' 和 'redux-cycles' react HOC。如何让它发挥作用?

javascript - 如何计算现在日期和恒定日期之间的差异。并像 1d,1m,1w 一样编辑它

spring - HTTP 状态 404 -/gwtspring/com.javacodegeeks.gwtspring.Application/Application.html

java - http 状态 404 – 在 Tomcat 服务器上的 jsp、servlet 中未找到

javascript - 为什么当所有函数都是 future 时,第三个函数不会在 pipeK 中被调用?

reactjs - React - socket.io on() 似乎没有做任何事情

python - Flask 教程 - 404 Not Found