首页 > 解决方案 > 我可以动态调用导入的文件名吗?

问题描述

我正在制作一个 7 天预测反应应用程序。我有一个图像文件夹,其中包含 28 个天气类型的图标,分为白天和夜晚版本。这些图像像这样被导入到一个组件中(为简洁起见,我将只显示 4 个选项):

import {
    dayclear, daycloudy,

    nightclear, nightcloudy
} from '../images'

根据调用此组件时的天气类型,我正在尝试动态命名图像源。有没有办法动态连接对象名称?前任:

<img src={this.props.timeOfDay + this.props.weather} alt="Weather Image" />

我正在寻找该来源最终成为导入图像的对象名称。

标签: javascriptreactjs

解决方案


尝试将图像存储在这样的对象中:

const IMAGES = {
  dayclear,
  nightclear,
  ...
}

然后创建一个天气名称

const { timeOfDay, weather } = this.props
const weatherName = `${timeOfDay > condition ? 'day' : 'night'}${weather}`

最后将其添加到图像的 src 中:

<img src={IMAGES[weatherName]} alt="Weather Image" />

推荐阅读