简体   繁体   English

反应内联背景图像

[英]React inline background image

I am trying to access the dynamically image from the public directory and using inline style to pass in the props in the Card.js and call it in CardComponent.js.我试图从公共目录访问动态图像并使用内联样式在 Card.js 中传递道具并在 CardComponent.js 中调用它。 I am very new to react.我很新来反应。 I don't know what I am doing wrong here.我不知道我在这里做错了什么。 Can you help me with this?你能帮我解决这个问题吗? Thanks!谢谢!

Here is the card I am trying to render:这是我要渲染的卡片:

在此处输入图片说明

Here is the directory of image I am trying to access : public/assets/img/talent.jpg这是我试图访问的图像目录: public/assets/img/talent.jpg

Card.js Code: Card.js 代码:

    import React from "react";
import "../styles/Card.css";

function Card(props) {
  return (
    <div>
      <div
        className="img-item"
        style={{
          backgroundImage: `url(require("/assets/img/"${props.image}))`,
        }}
      >
        <div className="text-center centered">
          <h3 className="reset-mp text-left mb-2">{props.cardTitle}</h3>
          <p className="reset-mp">{props.cardDescription}</p>
        </div>
      </div>
    </div>
  );
}

export default Card;

CardComponent.js code: CardComponent.js 代码:

    import React from "react";
import Card from "./Card";
import "../styles/CardComponent.css";

function CardComponent() {
  return (
    <div className="cards">
      <Card
        cardTitle="A Talent"
        cardDescription="Looking for a job"
        image="talent.jpg"
      />
    </div>
  );
}

export default CardComponent;

Everything inside the public folder is a static file, it will be copied exactly as it is during build in root. public 文件夹中的所有内容都是静态文件,它将在根目录中完全复制。

Here a better explanation 这里有更好的解释

So, in your case, you should be able to view you image on:因此,在您的情况下,您应该能够在以下位置查看您的图像:

  • http://127.0.0.1:3000/assets/img/talent.jpg

So, you can just use:所以,你可以使用:

<div style={{ backgroundImage: `url(/assets/img/${props.image})` }}>

尝试将此行/assets/img/更改为此./assets/img/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM