img 的相关事件
为什么要等待一个图片加载?
额, 也许当你的图片已经加载完了后你希望:
- 隐藏loading图标。
- 自动加载更多图片。
- 转化UI,使图片更加凸显。
- 或者其他理由
想要找出如何判断图片加载事件的方法,那么就接着往下读吧。
onLoad & onError
onload 和 onerror 这两个属性以及可以正常的在DOM<img>标签上使用了(HTMLImageElement),react 要使用驼峰格式来获取这个事件,这也是onLoad
and onError的来由。react的文档中已经提倡这么用了,但并没有讨论具体为什么要这么用(Image Events)
所以你只要添加 onLoad
and onError
这两个事件在你的react <img>标签中就行了。如果还是不够清楚,那么看看下面的代码栗子吧!
Short Example
这里是一个关于使用 onLoad 事件的简短的栗子, 想看更多详细的关于如何显示loading图直到图标加载完成的栗子, 就看看作者的下一篇文章(React Image Gallery)
下面的这个组件, ImageWithStatusText, 加载一张图片和和显示一段文本:'loaded' 或者 'failed to load'
import React from 'react'; class ImageWithStatusText extends React.Component { constructor(props) { super(props); this.state = { imageStatus: null }; } handleImageLoaded() { this.setState({ imageStatus: 'loaded' }); } handleImageErrored() { this.setState({ imageStatus: 'failed to load' }); } render() { return ( <div> <img src={this.props.imageUrl} onLoad={this.handleImageLoaded.bind(this)} onError={this.handleImageErrored.bind(this)} /> {this.state.imageStatus} </div> ); } } export default ImageWithStatusText;
.