问题描述
我正在尝试从这个 JSON 文件动态加载信息并将其插入到组件中。
{
"team": [
{
"id": "","name": "","role": "","bio": "","major": "","image": "akh.jpg"
},{
"id": "","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} />