[英]How to set background image in div using map from JSON in React
我在 React 数据文件中有一个这样的数组,我正在使用 .map() 方法在组件ProjectItem.js
中加载 JSON 数据。
我应该如何获取 object “图片”,将其渲染为功能组件中 map function 中名为ProjectItem
的 div 中的背景图像? 标题和类别对象出现在我的网络应用程序上,但图像未加载我只看到路径 url,请帮助谢谢。
截屏
数据.json
[
{
"id": 0,
"title": "Projecttitle1",
"category": "frontend development",
"picture": "../src/Assets/Images/Desktop/Portfolio_A4.png",
},
{
"id": 1,
"title": "Projecttitle2",
"category": "frontend development",
"picture": "../src/Assets/Images/Desktop/Portfolio_D4.png",
}
]
应用程序.js
import React from "react";
import projects from "./data.json";
const App = () => {
return (
<div className="projectItem">
{projects.map((el) => {
return (
<div key={el.id}
style={{
backgroundImage: `url(${el.picture})`,
width: 300,
height: 300
}}
>
<ul>
<li>{el.title}</li>
<li>{el.url}</li>
<li>{el.category}</li>
</ul>
</div>
);
})}
</div>
);
};
export default App;
图片的路径是它们在计算机上相对于项目文件夹的位置。 当您使用该路径显示图像时,浏览器会在本地托管服务器上查找它们,这意味着您必须提供这些图像,以便可以访问它们。 看看这个: https : //create-react-app.dev/docs/using-the-public-folder/
我会将图像上传到存储服务并用下载 URL 替换路径。
尝试将所有图像移动到公用文件夹中,然后在数组对象中设置实际的 url,如下所示 -
{"id" : 1,
"picture" : "/Assets/Images/Desktop/Portfolio_A4.png"
//url should start from the directory inside the public folder, the just above directory of the mentioned url is - /Public*/Assets/Images/Desktop/Portfolio-A4.png* (try passing the url inside * * only)
}
建议将所有与项目相关的图片保存在公用文件夹中,然后将公用文件夹内的目录中的路径传递给 url 属性。 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.