[Web 前端] React Js img 图片显示默认 占位符

cp from : https://blog.csdn.net/wyk304443164/article/details/77093339

没有考虑到兼容性,因为我们暂时只适配了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;