我正在制作一个 7 天预测 react 应用程序。我有一个图像文件夹,其中有 28 个天气类型图标,分为白天和夜间版本。这些图像像这样导入到组件中(为简洁起见,我将只显示 4 个选项):
import {
dayclear, daycloudy,
nightclear, nightcloudy
} from '../images'
根据调用此组件时的天气类型,我尝试动态命名图像源。有没有办法动态连接对象名称?例如:
<img src={this.props.timeOfDay + this.props.weather} alt="Weather Image" />
我正在寻找该源最终成为导入图像的对象名称。
最佳答案
尝试将图像存储在这样的对象中:
const IMAGES = {
dayclear,
nightclear,
...
}
然后创建一个天气名称
const { timeOfDay, weather } = this.props
const weatherName = `${timeOfDay > condition ? 'day' : 'night'}${weather}`
最后将其添加到图像的src中:
<img src={IMAGES[weatherName]} alt="Weather Image" />
关于javascript - 我可以动态调用导入的文件名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67732375/