React Js img 圖片顯示預設 佔位符
阿新 • • 發佈:2018-11-08
本問出自:
沒有考慮到相容性,因為我們暫時只適配了webkit。
也沒有考慮到懶載入,因為專案比較緊有需要加的朋友看react-lazyload,也比較簡單,現成的輪子
/**
* Created by wuyakun on 2017/8/11.
* 會顯示預設圖片的image
*/
import React from 'react';
class DefaultImage extends React.Component {
constructor(props) {
super (props);
this.state = {
src: this.props.src ? this.props.src : '',
}
}
handleImageLoaded() {
//載入完畢
}
handleImageErrored() {
//載入失敗
this.setState({
src: require('../../images/default.jpg')
});
}
render() {
let props = this .props;
let {src} = this.state;
return (
<img
{...props}
src={src}
onLoad={this.handleImageLoaded.bind(this)}
onError={this.handleImageErrored.bind(this)}
/>
);
}
}
export default DefaultImage;