在 React Create-React-App 引入圖片檔案的方法 (不包括 SVG 圖檔)

Angel
Its Ok to Make Mistakes
4 min readJan 22, 2019

使用 Webpack 打包的 React Create-React-App, ES6 並不支援<img / >標籤內以圖片路徑引用圖片,直接貼上 HTML template 會出現報錯,需使用 require / import 或搭配 Styled-Components 方式匯入。

引用圖片的方式有下列幾種:

  1. 使用 require 將圖檔引入
  2. 使用 import 檔案讓 Webpack 打包該檔案
  3. 使用 Styled-Components 以 CSS 的方式引入

方法一:使用 require 將圖檔引入 React

<img src={require('./img/background.jpg')} alt="Background"/>

或是

const background = require('./background.jpeg);

<img src={background} alt="Background"/>

方法二:使用 import 檔案讓 Webpack 打包該檔案 (比1推薦)

import React, { Component } from 'react';
import background from './img/background.jpg';
class App extends Component {

render() {
return (
<div className="App">
<img src={background} alt="Background" />;
</div>
);
}
}
export default App;

或是同樣的方法,使用 CSS Background 方式引入

import React, { Component } from 'react';
import Background from './img/background.jpg';
class App extends Component {

render() {
return (
<div className="App">
<div style={{background: `url(${Background})`, height: '160px'}}/>
</div>
);
}
}
export default App;

方法三:使用 Styled-Components 以 CSS 的方式引入

import styled from 'styled-components';
import background from './img/background.jpg';
const Background = styled.div`
background-image: url(${background});
height: 160px;
`;
class App extends Component {

render() {
return (
<div className="App">
<Background/>
</div>
);
}
}
export default App;

Styled-Components 也可以使用 props 動態傳入

import styled from 'styled-components';
import background from './img/background.jpg';
const Background = styled.div`
background-image: url(${props => props.img});
height: 160px;
`
class App extends Component {

render() {
return (
<div className="App">
<Background img={background} />
</div>
);
}
}
export default App;

備註:SVG 不適用上述方法

Say hello! 我是 Angel,這裏的內容如果有幫到你,希望能獲得一些拍手作為鼓勵 
工作上的合作歡迎隨時透過 Mail 聯繫我 contact@aneglho.design

Thanks for watching!

--

--

Angel
Its Ok to Make Mistakes

A web / UIUX designer, in digital entertainment industry, Taipei Taiwan.