[英]How to conditionally render a data url in Reactjs
我試圖根據文件夾中的 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.
你只需要使用img
元素的onError
。 這個想法是在調用onError
時將src
道具與您的備用圖像交換,並且當圖像不存在時將調用它。 這是一個 沙盒和代碼:
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 個不在它們應該在的位置,因此將被替換為備用圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.