react.js Replace img src onerror

后端 未结 22 3066
北恋
北恋 2020-11-29 00:20

I have a react component that is the detail view from a list.

I am trying to replace the image with a default image if the image does not exist and there is a 404 er

22条回答
  •  感情败类
    2020-11-29 01:19

    Arthur's answer will result in infinite callbacks if fallback image also fails.

    To avoid that, first set a state in the constructor for imageLoadError as true :

    constructor(props) {
        super(props);
        this.state = {
          imageLoadError: true,
        };
    }
    

    and then check for this state value in onError function to avoid infinite callbacks,

    the code will look like this :-

     { 
            if(this.state.imageLoadError) { 
                this.setState({
                    imageLoadError: false
                });
                e.target.src = 'fallbackImage.png';
            }
        }}
    />
    

提交回复
热议问题