React 如何動態加載本地圖片

react的標籤是<img>,導入本地圖片,可以用import加載

import React from 'react';
import testImgUrl from "../../images/1.png";
class App extends React.Component {
    constructor(props) {
        super(props);
     }
 
    render() {
       
        return (
         <div>
         <img src={testImgUrl}></img>
         </div>
        )
    }

}
export default App;

還可以用require

<img src={require("../../images/1.png")}></img>

試試網絡上的圖片

  <img src="http://a3.att.hudong.com/14/75/01300000164186121366756803686.jpg"></img>

將網絡圖片url定義成變量


const url = "http://a3.att.hudong.com/14/75/01300000164186121366756803686.jpg";

 <img src={url}></img>

到這裏都沒有什麼問題,假如要加載本地圖片,且require引入變量,如何實現

 <img src={require(`${url}`)}></img>

這個使用模板字符串可以拼接url

這麼寫會出錯

Error: Cannot find module '../../images/1.png'

我用了各種方式,得出了結論,require無法使用變量。

那麼就動態加載不了本地圖片嗎?

最後搜了一晚上,終於找到了方法

原文地址:https://www.coder.work/article/934601

let imgUrl = "../../images/1.png";
const reqSvgs = require.context('../../avatar/', true, /\.png$/);
const allSvgFilepaths = reqSvgs.keys();
const imagePath = allSvgFilepaths[0];
const image = reqSvgs(imagePath);
console.log(image);
this.state = {
url: image
};
<img src={this.state.url} ></img>

解釋一下,核心是這個require.context函數,參數分別是圖片所在目錄,是否遞歸查詢該目錄下的所有目錄,匹配文件的正則表達式

能搜到這個真的不容易

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章