首页 > 解决方案 > 如何将背景图像从 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>
    )
  }
}

标签: javascriptcssreactjs

解决方案


将图像添加到状态,并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>
    )
  }
}

推荐阅读