从 React 中的另一个文件导入图像

Import images from another file in React

我正在使用 create-react-app 构建一个简单的网页:

index.js:

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

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

它按预期工作,但我打算导入数十张图像,所以我决定将 import 调用移动到同一目录中的单独文件中:

images.js:

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

index.js:

import './images.js';

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

但是我得到 lostImage not defined 错误。我该如何正确执行此操作?

您需要从 images.js 文件中导出它们。然后导入到index.js文件中使用。

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} />
    );
}