[英]React: Switch images after load
我有一个由几个图像组成的组件。 用户执行操作时,需要重新加载这些图像。
目前,我通过将version
属性传递给props
来实现此目的,该属性作为查询参数附加到图像路径。 当用户执行该操作时,将对其进行更新并加载一组新的图像。
问题是,一个version
属性被更新,组件中的图像变为白色并开始单独加载,这看起来不太好。 理想情况下,我希望保留旧图像,直到所有新图像都已加载(可能在组件上覆盖了加载指示器),然后立即将它们全部切掉。
在React中如何处理?
好的,这会将一个虚拟图像放置在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.