score:1

ok this puts a dummy image in the dom (that should not show) and listens to it's onload event. when that fires, it will then update the src (manually, i.e. not via state) of the 'real' image element.

const img_width = 320;
const img_height = 240;
const baseimageurl = `http://loremflickr.com/${img_width}/${img_height}`;

const pics = [
  'https://img1.wsimg.com/fos/sales/cwh/8/images/cats-with-hats-shop-02.jpg',
  'https://img1.wsimg.com/fos/sales/cwh/8/images/cats-with-hats-og-image.jpg',
  'http://www.dispatch.com/content/graphics/2015/05/08/2-cats-in-hats-crafts-art-gof11etjd-1crafts-cats-in-hats-jpeg-03592-jpg.jpg',
  'http://www.dispatch.com/content/graphics/2015/05/08/2-cats-in-hats-crafts-art-gof11etjd-1crafts-cats-in-hats-jpeg-0b417-jpg.jpg',
  'https://i.ytimg.com/vi/cnycdffegbc/maxresdefault.jpg'
];

// this should really be hidden
// leaving it visible for, um, visibility
const hiddenimagestyle = {
  width: 100,
  height: 100,
};

class image extends react.component {
  constructor(props) {
    super(props);
    this.onnextimageload = this.onnextimageload.bind(this);
    this.nextimageurl = pics[0];
  }

  onnextimageload() {
    this.visibleimgel.src = this.nextimageurl;
  }

  render() {
    this.nextimageurl = pics[this.props.imageindex % 5];

    return (
      <div>
        <img
          ref={el => this.visibleimgel = el}
          width={img_width}
          height={img_height}
          src={pics[0]}
        />

        <img
          style={hiddenimagestyle}
          src={this.nextimageurl}
          onload={this.onnextimageload}
        />
      </div>
    );
  }
}

class imagecontroller extends react.component {
  constructor(props) {
    super(props);

    this.gotonextimage = this.gotonextimage.bind(this);

    this.state = {
      imageindex: 0,
    };
  }

  gotonextimage() {
    this.setstate({imageindex: this.state.imageindex + 1});
  }

  render() {
    return (
      <div>
        <image imageindex={this.state.imageindex} />

        <button onclick={this.gotonextimage}>
          next image
        </button>
      </div>
    );
  }
};

reactdom.render(<imagecontroller/>, document.getelementbyid('app'));

jsbin: https://jsbin.com/ramoxa/2


Related Query

More Query from same tag