【问题标题】:How to conditionally render a data url in Reactjs如何在 Reactjs 中有条件地呈现数据 url
【发布时间】:2021-05-11 09:19:50
【问题描述】:

我正在尝试根据文件夹中的 svg 文件不存在的条件有条件地呈现数据 url。我有一大堆 svg 文件正在进来,并由文件名动态引入。有一些 svg 不存在,所以我需要动态渲染一个带有大写文本的圆形图标作为图像的占位符。 我目前有:

我知道有一种方法,但我无法弄清楚这一点,并且在线上没有任何类似的解决方案。非常感谢任何帮助。谢谢!

Note: In case you are wondering how I am able to render svg files by using the img="" method, its because I did some configurations and added some packages to do the job.
 

【问题讨论】:

    标签: javascript reactjs react-native svg icons


    【解决方案1】:

    您只需要使用img 元素的onError 属性。这个想法是每当调用onError 时将src 属性与您的备用图像交换,并且当图像不存在时将调用它。这是Sandbox 和代码:

    import { Fragment, useRef } from "react";
    import "./styles.css";
    
    const img_array = [
      "images/icon1.png",
      "images/icon2.png",
      "https://lesspestcontrol.com.au/wp-content/uploads/green-tick.png"
    ];
    
    const fallback_img =
      "https://cdn.iconscout.com/icon/premium/png-256-thumb/broken-link-3-503014.png";
    
    export default function App() {
      const swapDefaultImage = (e) => (e.target.src = fallback_img);
    
      return (
        <div>
          {img_array.map((src, i) => (
            <Fragment key={i}>
              <img alt={`${src}`} onError={swapDefaultImage} src={src} />
              <br />
            </Fragment>
          ))}
        </div>
      );
    }
    

    这里有一个包含 3 个图像的数组,其中 2 个不在应有的位置,因此将替换为备用图像。

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 2011-10-19
      • 2021-09-22
      • 1970-01-01
      相关资源
      最近更新 更多