简体   繁体   English

无法在 ReactJS 中加载本地背景图片

[英]Can't load a local background image in ReactJS

I'm having some problems taking an image from my local machine with my React App.我在使用 React App 从本地机器拍摄图像时遇到了一些问题。

I'm trying to take image like我正在尝试拍摄图像

style={{ backgroundImage: `url(../../assets/images/games/${img}))`  }}

But it's not working, and I don't understand why.但它不起作用,我不明白为什么。

My file is located in我的文件位于

C:\Users\Me\Desktop\myreactapp\src\routes\GameSlider\index.js

And my images are in我的图像在

 C:\Users\Me\Desktop\myreactapp\src\assets\images\games

This is how my index.js looks now (without imports):这是我的index.js现在的样子(没有导入):

const GameSlider = ( { key, id,  name, img, minPrice, maxSlots } ) => {
    return (
        <div key={key}>
            <div className="home-games">
                <div className="img" style={{ backgroundImage: `url(../../assets/images/games/${img}))`  }} alt="..." />
                <div className="price">
                    <IntlMessages id="gameSlider.startingAt" />
                    <p>
                        <span className="min">{minPrice}</span> 
                        <span className="per-slot">
                            <IntlMessages id="gameSlider.perSlot" />
                        </span>
                    </p>
                </div>
                <span className="title">{name}</span>
                <div className="features">
                    <Col span={24} className="feature">
                        <Icon type="lock" /> <IntlMessages id="gameSlider.upTo" /> {maxSlots} <IntlMessages id="general.slots" />
                    </Col>
                </div>
                <Link to={`/order/${id}`}><Button className="comet-buy-button" style={{ background: 'rgb(241,89,89)', borderRadius: '20px' }}>BUY NOW!</Button></Link>
            </div>
        </div> 
    );
}

export default GameSlider;

Absolute path and relative path is always one of the issue for developers to fix :P so there is a another way to solve this easily.绝对路径相对路径始终是开发人员要解决的问题之一 :P 所以有另一种方法可以轻松解决这个问题。

You can use something like this:你可以使用这样的东西:

import the whatever image in the namespace导入命名空间中的任何图像

import backgroundImg from '../images/BackgroundImage.jpg';

then use it the element like this然后像这样使用它的元素

 <img src={backgroundImg} />

let me know if this works.让我知道这个是否奏效。

如果你想使用一个或多个图像而不导入它们,你应该把你的资产文件夹放到公共文件夹中,然后像下面这样使用它们:

src='/assets/images/pic.jpeg'

1 - Import your img: 1 - 导入您的 img:

import img from '../../pics/asteroids.jpg'

2 - And then use it: 2 - 然后使用它:

<div style={{backgroundImage: `url(${img})`}}>Test</div>

On your page this div will look like this:在您的页面上,此 div 将如下所示:

<div style="background-image: url(&quot;/static/media/asteroids.c8ab11b3.jpg&quot;);">Test</div>

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

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