javascript - 如何将背景图像从 React 中的状态映射到卡片上?
问题描述
我的 React 应用程序的一个页面上有三张卡片。我已经完美地将标题和文本内容映射到卡片上,但是在弄清楚如何将背景图像映射到卡片上时遇到了麻烦。使用行星对象如何使每张卡片的背景成为导入的图像?
import React, { Component } from "react";
import { Link } from "react-router-dom";
import mars from "../images/mars.jpg";
import venus from "../images/venus.jpg";
import titan from "../images/titan.jpg";
export default class Planets extends Component {
state = {
planets: [
{
planet: "",
title: "Mars",
info:
"red planet"
},
{
planet: "",
title: "Venus",
info:
"gaseous planet"
},
{
planet: "",
title: "Titan",
info:
"moon"
}
]
};
render() {
return (
<section style={{
backgroundColor: 'black', height: '100vh'}} className="planets">
<div className="planets-center">
{this.state.planets.map(item => {
return (
<Link to="/rooms">
<div className="planets-card">{item.icon}
<article key={`item-${item.title}`} className="planets">
<h6>{item.title}</h6>
<p>{item.info}</p>
</article>
</div>
</Link>
);
})}
</div>
</section>
)
}
}
解决方案
将图像添加到状态,并backgroundImage
通过 style属性设置为
<div className="planets-card" style={{ backgroundImage: `url(${item.bgUrl})` }}>
示例(未测试):
import mars from "../images/mars.jpg";
import venus from "../images/venus.jpg";
import titan from "../images/titan.jpg";
export default class Planets extends Component {
state = {
planets: [{
planet: "",
title: "Mars",
info: "red planet",
bgUrl: mars,
},
{
planet: "",
title: "Venus",
info: "gaseous planet",
bgUrl: venus,
},
{
planet: "",
title: "Titan",
info: "moon",
bgUrl: titan,
}
]
};
render() {
return (
<section style={{
backgroundColor: 'black', height: '100vh'}} className="planets">
<div className="planets-center">
{this.state.planets.map(item => {
return (
<Link to="/rooms">
<div className="planets-card" style={{ backgroundImage: `url(${item.bgUrl})` }}>{item.icon}
<article key={`item-${item.title}`} className="planets">
<h6>{item.title}</h6>
<p>{item.info}</p>
</article>
</div>
</Link>
);
})}
</div>
</section>
)
}
}
推荐阅读
- python - TypeError: localize_file() 接受 1 个位置参数,但给出了 2 个
- c# - 如何将字符串属性中的值分配给属性对象
- wordpress - 将代码与 wordpress 中的模板页面分开(单独的视图和代码)
- reactjs - 我可以将反应道具传递给组件的下一个/图像吗
- c# - 实体框架多对多关系查询
- firebase - 谷歌卡在登录屏幕上叹了口气
- typescript - 逗号运算符的左侧未使用且没有副作用
- properties - antform:如何在 a 中显示属性值
- c# - 如何访问 JArray 中不同级别的嵌套 JObject 的值以将它们导出到 CSV 文件?
- matlab - 读取大量数据的最佳方式