React中img标记中的onError

时间:2016-07-28 03:32:16

标签: html image reactjs onerror

我想用react中的默认图像替换断开的链接。我通常会使用onerror,但它没有按预期工作。具体来说,我遇到了“在现有状态转换期间无法更新(例如render内)”的重复错误。最终,出现默认图像,但需要很长时间(此错误的许多打印)。这是一个非常类似的问题:react.js Replace img src onerror。我尝试了这个解决方案(第一个,不使用jQuery),但它导致了所描述的错误。我猜onError必须不断被触发,从而导致不断重新渲染。任何替代解决方案/修复方法?

   import React from 'react';
import { connect } from 'react-redux';
//import AddImageModal from '../components/AddImageModal.js';
import Button from 'react-bootstrap/lib/Button';
//import { getPostsByUserId } from 'actions'
import Posts from '../components/Posts.js';
var Modal = require('react-modal');
require('../../styles/AddImageModal.scss');
import { save_post } from '../actions';

 const customStyles = {
  content : {
    top                   : '50%',
    left                  : '50%',
    right                 : 'auto',
    bottom                : 'auto',
    marginRight           : '-50%',
    transform             : 'translate(-50%, -50%)'
  }
};

var MyWallScreen = React.createClass({

  getInitialState: function() {
    return { 
      modalIsOpen: false,
      imageUrl: "" 
    };
  },

  openModal: function() {
    this.setState({modalIsOpen: true});
  },

  afterOpenModal: function() {
    // references are now sync'd and can be accessed. 
    this.refs.subtitle.style.color = '#f00';
  },

  closeModal: function() {
    this.setState({modalIsOpen: false});
  },

  setUrl: function(e,val) 
  {
    if (e.keyCode === 13) 
        {
          this.setState({
            imageUrl: val
          });
        }
  },

  resetImageUrl: function()
  {
    this.setState({
      imageUrl: ""
    });
  },

  onError: function() {
    this.setState({
      imageUrl: "default.jpg"
    });
  },


  render: function() {
    const { userPosts, dispatch } = this.props;
    return (
      <div>
        <button onClick={this.openModal}>Add Image</button>

        {/* The meat of the modal. */}
        <Modal
          isOpen={this.state.modalIsOpen}
          onAfterOpen={this.afterOpenModal}
          onRequestClose={this.closeModal}
          style={customStyles} >

        <div className="modalBox">
          <h2 className="modalBanner">Add an image link</h2>
          <input ref="urlInput" 
                className="modalInput"
                onKeyDown={e=>this.setUrl(e,this.refs.urlInput.value)}/>
          {this.state.imageUrl ?
            <img className="modalImage" 
                  src={this.state.imageUrl}
                  onError={this.onError()}/>
            :<div className="modalImage"></div>
          }
          <div>
            <Button className="modalButton" bsStyle = "success" 
                onClick = {() => {
                dispatch(save_post(0,this.state.imageUrl));
                this.closeModal();
                this.resetImageUrl();
                }}>
                Post
            </Button>
            <Button className="modalButton" bsStyle = "danger" 
                onClick = {() => {
                  this.closeModal();
                  this.resetImageUrl();
                }}>
                Cancel
            </Button>
          </div>
        </div>
        </Modal>


        <Posts posts={userPosts}/>
      </div>
    );
  }
});


function mapStateToProps(state, ownProps) {
  return {
    userPosts: state.posts[0]
  }
}


MyWallScreen = connect(mapStateToProps)(MyWallScreen);

export default MyWallScreen;

2 个答案:

答案 0 :(得分:7)

代码调用this.onError而不是传递对它的引用。每次拨打render都会致电this.onError()。删除括号,看看是否修复了它:

<img className="modalImage" 
  src={this.state.imageUrl}
  onError={this.onError()}/> // `onError` is being called here

修正版:

<img className="modalImage" 
  src={this.state.imageUrl}
  onError={this.onError}/> // `onError` is being passed as a reference here

答案 1 :(得分:5)

您可以替换图像损坏的链接,而无需保持图像网址状态。

<img
 onError={(event)=>event.target.setAttribute("src","default-image-link")}
 src="image-broken-link"
/>