react.js Replace img src onerror

后端 未结 22 3076
北恋
北恋 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:25

    Ran into a similar problem and the best solution i could find was Georgii Oleinikov's answer. (Doesn't require making new imageLoadError state as suggested by Nitesh Ranjan in his answer)

    onError={(e)=>{ if (e.target.src !== "image_path_here"){
                        e.target.onerror = null;
                         e.target.src="image_path_here";}
                    }
               }
    

    e.target.onerror = null is not needed (and doesn't really help) because the if condition is enough to prevent the infinite loop(if backup image fails to load as well).

    So:

    onError={(e)=>{ if (e.target.src !== "image_path_here"){
                     e.target.src="image_path_here";}
                   }
             }
    

    EDIT: The other way around is to set a flag outside the return brackets and check for the flag in the if statement. Code should look something like this:

    render(){
     let errorflag=true;
     return(
                { if (errorflag){ errorflag=false; e.target.src=url; } }} />
                );
    } 
    

提交回复
热议问题