简体   繁体   中英

Import images from another file in React

I am using create-react-app to build a simple web page:

index.js:

import lostImage from './assets/img/illustrations/lost.svg';

function Image(props) {
    return (
        <img src={lostImage} />
    );
}

It works as expected, however I plan to import dozens of images, so I decided to move the import calls in a separate file in the same directory:

images.js:

import lostImage from './assets/img/illustrations/lost.svg';

index.js:

import './images.js';

function Image(props) {
    return (
        <img src={lostImage} />
    );
}

However I get the lostImage not defined error. How do I properly do this?

You need to export them from images.js file. Then import them to the index.js file to use.

images.js:

import lostImage from './assets/img/illustrations/lost.svg';
export { lostImage };

index.js:

import {lostImage} from './images.js';

function Image(props) {
    return (
        <img src={lostImage} />
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM