踩坑小記錄( • ̀ω•́ )✧
在剛接觸React時就覺得她是一個傲嬌的小姐姐
想不到圖片插入的方式也是那么特別呢 (ฅωฅ*)
首先,用create-react-app搭建的react項目會以public文件夾為根目錄~
With create-react-app
there is public folder (with index.html...). If you place your "myImage.png" there, say under img sub-folder, then you can access them through:
<img src={window.location.origin + '/img/myImage.png'} />'
其次,Relative imports outside of src/ are not supported. 通過相對路徑導入圖片是不支持的
所以想要在項目中用本地圖片的最好方式是在項目的public文件夾建一個子目錄imgs以存放圖片/視頻等公用文件,
在需要用到的時候,因為public文件夾是accessible的,所以只需要/imgs/文件名就可以讀取該文件了
-----------------------------------------------------------------------------------------------------------------------------------
或者是把圖片放在js文件夾里,通過相對路徑導入到js文件中
附上一個stackoverflow關於此討論的鏈接