最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React use img onerror - Stack Overflow

programmeradmin1浏览0评论

I create a Image component

class Image extends React.Component {
  render() {
    return (
      <img src= { this.state.imgUrl } onError ={ this.onError() }/>
    );
  }
  onError(){
      console.log('Image onError');
        this.setState(
      { imgUrl: '../default.png' }
    );
  }
}

and use it in my view but if one Image not found. all Image Component In view onError

I create a Image component

class Image extends React.Component {
  render() {
    return (
      <img src= { this.state.imgUrl } onError ={ this.onError() }/>
    );
  }
  onError(){
      console.log('Image onError');
        this.setState(
      { imgUrl: '../default.png' }
    );
  }
}

and use it in my view but if one Image not found. all Image Component In view onError

Share Improve this question edited Apr 5, 2016 at 7:09 Brigand 86.2k20 gold badges167 silver badges173 bronze badges asked Apr 5, 2016 at 6:36 AhnQirajAhnQiraj 531 gold badge1 silver badge3 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17

Remember, if you want to change the styles of the element and/or change the img source, just do something like this:

<img
  src={'original src url goes here'}
  alt="example"
  onError={(e) => {
     e.target.src = '/example/noimage.png' // some replacement image
     e.target.style = 'padding: 8px; margin: 16px' // inline styles in html format
  }}
/>

Hope it helps!

You have onError={this.onError()} with instant function call. It should be either onError={this.onError.bind(this)} or onError={() => this.onError()}.

As React versions are updated, we recommend using the following code.

<img
  src={'original src url goes here'}
  alt="example"
  onError={(e) => {
     e.currentTarget.src = '/example/noimage.png' // some replacement image
  }}
/>
发布评论

评论列表(0)

  1. 暂无评论