[英]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.