react.js Replace img src onerror

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

    If anyone is using image src with require then onError doesn't work as -

    {props.name}
    

    then require throws an error, where I tried multiple ways and came to try and catch block solution as -

      let imgSrc;
      try {
        imgSrc = require(`./../../assets/images/${props.imgName}.png`);  
      } catch {
        imgSrc = require(`./../../assets/images/default.png`);
      }
    

    and use as

    {props.name}
    

提交回复
热议问题