React:加载后切换图像

时间:2016-07-17 22:08:42

标签: javascript reactjs

我有一个由几张图片组成的组件。当用户执行操作时,需要重新加载这些图像。

目前我通过将version属性传递给props来实现此目的,该version属性作为查询参数附加到图像路径。当用户执行操作时,会更新并加载一组新图像。

问题是,$summary_fields属性更新后,组件中的图像会变为白色,并开始单独加载,看起来并不是很好。理想情况下,我想要保留旧图像,直到所有新图像都已加载(可能加载指示符覆盖在组件上),然后立即将它们全部切换出来。

如何在React中找到它?

1 个答案:

答案 0 :(得分:1)

好的,这会在DOM中显示一个虚拟图像(不应该显示)并监听它的onLoad事件。当它触发时,它将更新'真实'图像元素的src(手动,即不通过状态)。

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