![](/img/trans.png)
[英]Next.js: Module build failed: Error: Cannot find module 'react-hot-loader/babel' from '/home/ugurkaya/Desktop'
[英]Loading image location from JSON file dynamically - (Cannot find module…) React, Next.js
我正在尝试从此 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 元素,因为 rest 工作正常。
<img className="" src={require(props.image)}></img>
如果我取出 img 元素或放入实际路径,它会完美运行,但这种方式不起作用。 我能找到的唯一类似的帖子是这个,但它从未得到答案。 StackOverflow:动态导入图像(React Js)(需要 img 路径找不到模块)
更新代码 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
并且可以正常工作! 我不得不删除最后一个/
并且它起作用了。
在 NextJS 中,图像是从/
(root) 提供的,因此您不必在路径中使用public
,或者为此使用require
。 只需生成一个标准字符串。 它应该像...一样简单
import aboutJson from './about.json'
const teams = aboutJson[teams]
const basePath = '/images/profiles/'
const Teams = () => (
<ul>
{teams.map((person) => <ProfileCard
key={person.id}
id={person.id}
name={person.name}
role={person.role}
major={person.major}
image={`${basePath}/${person.image}`}
/>
)}
</ul>
)
const ProfileCard = ({ image, ...props }) => <img src={image} />
此外,next 确实提供了自己的图像组件:
import Image from 'next/image'
const ProfileCard = ({ image, ...props }) => <Image src={image} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.