2017-05-06 132 views
10

我正嘗試在我的某個反應組件中導入圖像文件。我有項目設置與網絡包如何在React組件中導入圖像(.svg,.png)

這裏是我的組件

import Diamond from '../../assets/linux_logo.jpg'; 

export class ItemCols extends Component { 
    render(){ 
     return (
      <div> 
       <section className="one-fourth" id="html"> 
        <img src={Diamond} /> 
       </section> 
      </div> 
     ) 
    } 
} 

這裏是我的項目結構的代碼。

enter image description here

我安裝我的webpack.config.js文件以下列方式

{ 測試:/.(jpg|png|svg)$/, 裝載機:「URL裝載機」, 選項:{ 上限:25000, }, },{ 測試 :/.(jpg|png|svg)$/, 裝載機: '文件加載器', 選項:{ 名稱: '[path] [name]。[hash]。[ext]', }, },

PS。我可以從任何其他遠程源獲取圖像,但不能保存本地保存的圖像。 JavaScript控制檯也不會給我任何錯誤。請任何幫助。我很新的反應,無法找到我做錯了什麼。

+0

Shadid嘗試,你有沒有嘗試? –

+0

是的,我試過。再次在控制檯沒有錯誤,但我看不到圖像 – Shadid

+0

您應該做一個webpack生成並檢查圖像的存儲位置。在img src中使用該路徑。 – vijayst

回答

24

使用

import mainLogo from'./logoWhite.png'; 
 

 
//then in the render function of Jsx insert the mainLogo variable 
 

 
class NavBar extends Component { 
 
    render() { 
 
    return (
 
     <nav className="nav" style={nbStyle}> 
 
     <div className="container"> 
 
      //right below here 
 
      <img src={mainLogo} style={nbStyle.logo} alt="fireSpot"/> 
 
     </div> 
 
     </nav> 
 
    ); 
 
    } 
 
}

+1

如果我想導入10個圖像會發生什麼? –

+0

@LeoGasparrini - 我不確定我明白你在問什麼 - 只要你在導入時給他們一個獨特的名字,你應該可以導入任意多的數據,不是嗎? –