我的 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>
)
}
}
最佳答案
将图像添加到状态,并通过 style 属性设置为 backgroundImage
<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>
)
}
}
关于javascript - 如何将背景图像从 React 中的状态映射到卡片上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120329/