Javascript 如何将背景图像从React中的状态映射到卡上?
在我的React应用程序中,一页上有三张卡片。我已经将标题和文本内容映射到了卡片上,但是我很难弄清楚如何将背景图像映射到卡片上。使用行星物体,我将如何使每张卡片的背景成为导入的图像Javascript 如何将背景图像从React中的状态映射到卡上?,javascript,css,reactjs,Javascript,Css,Reactjs,在我的React应用程序中,一页上有三张卡片。我已经将标题和文本内容映射到了卡片上,但是我很难弄清楚如何将背景图像映射到卡片上。使用行星物体,我将如何使每张卡片的背景成为导入的图像 import React, { Component } from "react"; import { Link } from "react-router-dom"; import mars from "../images/mars.jpg"; import venus from "../images/venus.jp
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>
)
}
}
import React,{Component}来自“React”;
从“react router dom”导入{Link};
从“./images/mars.jpg”导入火星;
从“./images/venus.jpg”导入维纳斯;
从“./images/titan.jpg”导入titan;
导出默认类扩展组件{
状态={
行星:[
{
行星:“,
标题:“火星”,
信息:
“红色星球”
},
{
行星:“,
标题:“维纳斯”,
信息:
“气态行星”
},
{
行星:“,
标题:“泰坦”,
信息:
“月亮”
}
]
};
render(){
返回(
{this.state.planets.map(项=>{
返回(
{item.icon}
{item.title}
{item.info}
);
})}
)
}
}
将图像添加到状态,并通过样式属性设置为backgroundImage
<div className="planets-card" style={{ backgroundImage: `url(${item.bgUrl})` }}>
示例(未测试):
从“./images/mars.jpg”导入火星;
从“./images/venus.jpg”导入维纳斯;
从“./images/titan.jpg”导入titan;
导出默认类扩展组件{
状态={
行星:[{
行星:“,
标题:“火星”,
信息:“红色星球”,
bgUrl:mars,
},
{
行星:“,
标题:“维纳斯”,
信息:“气态行星”,
bgUrl:venus,
},
{
行星:“,
标题:“泰坦”,
信息:“月亮”,
bgUrl:titan,
}
]
};
render(){
返回(
{this.state.planets.map(项=>{
返回(
{item.icon}
{item.title}
{item.info}
);
})}
)
}
}
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>
)
}
}