简体   繁体   English

如何有条件地在 Reactjs 中呈现数据 url

[英]How to conditionally render a data url in Reactjs

I am trying to conditionally render a data url based on the condition that the svg file from a folder does not exist.我试图根据文件夹中的 svg 文件不存在的条件有条件地渲染数据 url。 I have a whole bunch of svg files that are coming in and is being brought in dynamically by the name of the file.我有一大堆 svg 文件正在进来,并由文件名动态引入。 There are some svg's that do not exist and so I would need to dynamically render a circle shaped icon with a capital text as a placeholder for the image.有一些 svg 不存在,所以我需要动态渲染一个带有大写文本的圆形图标作为图像的占位符。 I currently have:我目前有:

I know there is a way, but I havent been a able to figure this out and there arent any similar solutions online.我知道有一种方法,但我无法弄清楚这一点,也没有任何类似的在线解决方案。 Would really appreciate any help.非常感谢任何帮助。 Thanks!谢谢!

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.
 

You just need to use the onError prop of the img element.你只需要使用img元素的onError The idea is to swap the src prop with your fallback image whenever the onError is called, and it's going to be called when an image does not exist.这个想法是在调用onError时将src道具与您的备用图像交换,并且当图像不存在时将调用它。 Here is a Sandbox and the code:这是一个 沙盒和代码:

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>
  );
}

Here you have an array of 3 images, 2 of which are not where they're supposed to be and thus will be replaced with the fallback image.在这里,您有一个包含 3 个图像的数组,其中 2 个不在它们应该在的位置,因此将被替换为备用图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM