我正在尝试从此 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
并且有效!我必须删除最后一个 /
并且它起作用了。
最佳答案
在 NextJS 中,图像是从 /
(根)提供的,因此您不必在路径中使用 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} />
关于javascript - 动态从 JSON 文件加载图像位置 - (找不到模块...)React、Next.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65362902/