图片导入
路径
绝对路径
'/create/video/images/index/pagel/xxx.png'
相对路径
'./images/index/pagel/xxx.png'
单个引入
import导入
import { Component } from 'react/cjs/re act.production.min';
import img1 from "./images/01.jpg"
class App extends Component{
constructor(props) {
super(props)
}
render() {
const { iconList,cache } = this.state
console.log(cache);
return (
<div className="App" >
<img src={img1} />
</div>
);
}
}
export default App;
require导入
import { Component } from 'react/cjs/react.production.min';
class App extends Component{
constructor(props) {
super(props)
}
render() {
const { iconList,cache } = this.state
console.log(cache);
return (
<div className="App" >
<img src={require("./images/01.jpg").default} />
</div>
);
}
}
export default App;
注意:
require
导入的是对象,需要指定属性名default
批量引入
import { Component } from 'react/cjs/react.production.min';
class App extends Component{
constructor(props) {
super(props)
this.state = {
cache:{},
iconList: [
{ name: '01', url:"./01.jpg" },
{ name: '02', url: "./02.jpg" },
{ name: '03', url: "./03.jpg" },
]
}
}
componentDidMount() {
const cache = {};
const context = require.context("./images", false, /.jpg$/)
context.keys().forEach(key => {
cache[key] = context(key).default
});
this.setState({ cache })
}
render() {
const { iconList,cache } = this.state
console.log(cache);
return (
<div className="App" >
{
iconList.map((item,key) => {
return (
<div key={key}>
{item.name}
<img src={cache[item.url]} />
</div>
)
})
}
</div>
);
}
}
export default App;
注意:
require
导入的是对象,需要指定属性名default
参考文章: