React 中引入本地圖片和背景圖片的方法
阿新 • • 發佈:2019-01-24
1、在webpack.config中找到相應的圖片路徑的縮寫配置(不是所有的專案都有縮寫配置的,在大型專案中為了書寫方便進行縮寫配置)
所以我的圖片都在縮寫路徑 Image 裡面
2、接下來就要說引入圖片的方式了
如果不是背景圖片的話,有以下兩種方式
①直接在內部引用
②使用import方法
import img from 'Image/weixin_erweima.png' //引入圖片的路徑
<img src={img} /> //變數的方式引入圖片,記得用{}大括號來進行引用
2、如果是背景圖片原理和上面是一樣的
①直接定義引入
//在render()內定義
const bgGround={
display:'inline-block',
height: '40px',
width:'40px',
background: `url(${require("Image/weixin_erweima.png")})`
}
②使用import方法
import img from 'Image/weixin_erweima.png';
//在render()內定義
const bgGround = {
display:'inline-block',
height: '40px',
width:'40px' ,
backgroundImage: 'url(' +img + ')'//圖片的路徑
};
//最後在return中進行書寫
<p>
<span style={bgGround}></span>家樂園餐廳
</p>