后端返回图片或者json错误 ,前端加载和隐藏错误图片

利用 img 的 onLoad 和 onError 方法:

import React from 'react';

class ImgLoad extends React.Component {
constructor(props) {
super(props);
this.state = { imageStatus: null,isError:true };
}

handleImageLoaded() {
this.setState({ imageStatus: '已加载',isError:false });
}

handleImageErrored() {
this.setState({ imageStatus: '加载失败',isError:true });
}

render() {
return (
<div>
<img style={this.state.isError? {display:'none'}:{}}
src={this.props.imageUrl}
onLoad={this.handleImageLoaded.bind(this)}
onError={this.handleImageErrored.bind(this)}
/>
{this.state.imageStatus}
</div>
);
}
}
export default ImgLoad;

调用方法

import ImgLoad from './ImgLoad';



<ImgLoad imageUrl="错误img"></ImgLoad>
<ImgLoad imageUrl="正确img"></ImgLoad>