Is it possible to import a group of images as an array? (create-react-app project) like written below but as a single-line?
import Hat1 from '../../assets/img/accesories/hats/hat1.png';
import Hat2 from '../../assets/img/accesories/hats/hat2.png';
import Hat3 from '../../assets/img/accesories/hats/hat3.png';
import Hat4 from '../../assets/img/accesories/hats/hat4.png';
import Hat5 from '../../assets/img/accesories/hats/hat5.png';
import Hat6 from '../../assets/img/accesories/hats/hat6.png';
const hatsArr = [
Hat1,
Hat2,
Hat3,
Hat4,
Hat5,
Hat6
];
You can't directly import them as an array but you can use a file dedicated to these imports :
images.js :
import Hat1 from '../../assets/img/accesories/hats/hat1.png';
import Hat2 from '../../assets/img/accesories/hats/hat2.png';
import Hat3 from '../../assets/img/accesories/hats/hat3.png';
import Hat4 from '../../assets/img/accesories/hats/hat4.png';
import Hat5 from '../../assets/img/accesories/hats/hat5.png';
import Hat6 from '../../assets/img/accesories/hats/hat6.png';
export default [
Hat1,
Hat2,
Hat3,
Hat4,
Hat5,
Hat6
];
Then import this array in one line in other files :
import hatsArr from './images';
Edit : I think you can do some tricky stuff in webpack.config.js
to achieve this one line import but can't help on that.
You can write a separate file to export those images like below:
var AppData = {
adata: {
"initialdata":[
{
"text":"",
"image":"images/slider1.png"
},
{
"text":"",
"image":"images/slider2.png"
},
{
"text":"",
"image":"images/slider3.png"
}
]
}
}
export default AppData;
and import it in your component like below:
import AppData from './AppData';
class App extends Component {
constructor() {
super();
this.state = AppData.adata;
}
render() {
return (
<ul className="slider">
{this.state.initialdata.map(function(item,index) {
return (
<li key={index}>
<img className="sliderImage" src={`./${item.image}.png`} role="presentation" alt="image"/>
</li>
)
},this)}
</ul>
);
}
}
Hope this would help and working demo by exporting,importing like this demo
I have a hybrid of a solution of what has been mentioned here
import Hat1 from '../../assets/img/accesories/hats/hat1.png';
import Hat2 from '../../assets/img/accesories/hats/hat2.png';
import Hat3 from '../../assets/img/accesories/hats/hat3.png';
import Hat4 from '../../assets/img/accesories/hats/hat4.png';
import Hat5 from '../../assets/img/accesories/hats/hat5.png';
import Hat6 from '../../assets/img/accesories/hats/hat6.png';
export const hatsArr = [
Hat1,
Hat2,
Hat3,
Hat4,
Hat5,
Hat6
];
... your logic goes here ...
Notice that all you have to do is add export
in front of you const
.
This way you can have your images AND your logic in ONE file at the cost of just one keyword.
来源:https://stackoverflow.com/questions/48560592/is-it-possible-to-import-a-group-of-images-as-an-array-create-react-app-projec