【发布时间】:2021-03-29 10:53:28
【问题描述】:
我正在尝试从这个 JSON 文件动态加载信息并将其插入到组件中。
{
"team": [
{
"id": "",
"name": "",
"role": "",
"bio": "",
"major": "",
"image": "akh.jpg"
},
{
"id": "",
"name": "",
"role": "",
"bio": "",
"major": "",
"image": "chr.jpg"
}
]
}
我的代码位置是/pages/about/index.js,我的JSON文件是/pages/about/about.json。
我解析代码的方式是这样的:
var data = require('./about.json')
var teams = data['team'];
<ul>
{teams.map((person) => {
var basePath = "/public/images/profiles/";
var loc = require(basePath + person.image);
return <ProfileCard key={person.id} id={person.id} name={person.name} role={person.role} major={person.major} image={loc} />
})}
</ul>
组件位于同一个文件中。我只附加配置文件中的 img 元素,因为其余的工作正常。
<img className="" src={require(props.image)}></img>
如果我取出 img 元素或放入实际路径,它可以完美运行,但这种方式不起作用。我能找到的唯一类似的帖子是这个,但它从未得到答案。 StackOverflow: importing image dynamically (React Js) (Require img path cannot find module)
更新代码 1:
<ul>
{teams.map((person) => {
var basePath = "/public/images/profiles/";
return <ProfileCard
key={person.id}
id={person.id}
name={person.name} r
role={person.role}
major={person.major}
image={`${basePath}/${person.image}`} />
})}
</ul>
而组件去掉require()之后就是这个样子了。
<img src={props.image}></img>
更新的代码 2:
从 img 切换到 next/image 并且可以正常工作!我不得不删除最后一个 / 并且它起作用了。
【问题讨论】:
标签: javascript json reactjs next.js nextjs-image