我正在构建一个简单的react组合应用程序。我的投资组合项目的信息存储在一个JSON文件中。
当我尝试使用portfolio项的图像代码时,它没有返回正确的路径。相反,它返回路径应该所在的位置“object Module]”。
代码:
import React, { Component } from 'react';
export default class WorkItemFocus extends Component {
...
render() {
if (this.props.activeItemId === '') {
return (
<div className="text-center">
<p>Please select an item below to view more details.</p>
</div>
)
} else {
const { name, description, tags, img_code } = this.props.activeItem;
return (
...
<img
src={require(`../assets/img/${img_code}`)}
alt={name}
/>
...
)
}
}
}
我在网上看了看,大部分都说我不是在使用webpack。我的package-lock.json文件说它安装在react-scripts下面。
我两个月前刚刚为别人做过这件事,并没有遇到这个问题。我是不是遗漏了什么?
在这篇文章中找到了答案:Webpack file-loader输出[对象模块]
需要添加。默认代码。
<img
src={require(`../assets/img/${img_code}`).default}
alt={name}
/>
(我希望我不是外面唯一一个贴出问题,贴出后直接找到答案,然后一两个小时就觉得哑巴的人)