小编典典

创建反应应用程序未在开发或构建中加载CSS背景图像

reactjs

我遇到一些无法加载背景图片的问题。我对最初的create react应用进行了一些重大修改,我的文件夹结构如下:

注意:我已经省略了一些文件和文件夹,如果您需要更多文件和文件夹,请告诉我。

App/
 node_modules/
 src/
  client/
   build/
   node_modules/
   public/
   src/
    css/
     App.css
    images/
     tree.png
     yeti.png
    App.jsx
  server/
 package.json
 Procfile

以下是创建此问题的步骤:

$ cd src/server && npm run dev

这将启动开发服务器并打开浏览器进入我的应用程序,除页面上的某些元素未显示图像外,其他所有功能均正常运行。

注意:我加载了一个图像 yeti.png ,这很好。

App.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import './css/App.css';
import yeti from './images/yeti.png';

const Footer = function(props) {
  return (
    <div>
      <Yeti />
      <Trees />
    </div>
    );
};

const Yeti = function(props) {
  return (        
      <img
        src={yeti}
        className="yeti yeti--xs"
        alt="Yeti"
      />
    );
};

const Trees = function(props) {
  return (        
      <div className="trees">
        <div className="trees__tree trees__tree--1"></div>
        <div className="trees__tree trees__tree--2"></div>
      </div>
    );
};

ReactDOM.render(
  <Footer />,
  document.getElementById('root')
);

App.css

.trees {
    bottom: 0;
    height: 110px;
    left: 0;
    position: fixed;
    width: 100%;
    z-index: 1;
}

.trees__tree {
    background-size: 30px;
    background: url('../images/tree.png') no-repeat;
    float: left;
    height: 50px;
    width: 30px;
}

.trees__tree--1 {
    margin: 0 0 0 6%;
}

.trees__tree--2 {
    margin: 2% 0 0 4%;
}

当我检查Chrome中的元素时,图像的路径似乎正确。当我将鼠标悬停在检查器的“样式”选项卡中图像的路径上时,将显示图像。

样式来源

请注意,我导入的图像的路径类似于背景图像的路径:

在此处输入图片说明

如果要导入tree.pngas import tree from './images/tree.png';并将两个<div>元素更改为<img src={tree} role="presentation" className="trees__tree trees__tree--1" /><img src={tree} role="presentation" className="trees__tree trees__tree-- 2" />则图像当然会加载。

如何显示背景图像?我的应用中还有其他背景图片无法加载,因此前面提到的创可贴对我没有帮助。恐怕会弹出我的应用并弄乱配置。

构建应用程序时,我也遇到同样的问题。

如果您需要查看更多源代码,可以在https://github.com/studio174/ispellits上进行查看,但请记住,我已经简化了此示例以找出问题所在。我遇到的问题实际上在Footer.jsxFooter.css


阅读 197

收藏
2020-07-22

共1个答案

小编典典

该问题纯粹是App.css文件中CSS的问题:

App.css

.trees__tree {    
    background: url('../images/tree.png') no-repeat;
    background-size: 30px; /** moved this property down */
    float: left;
    height: 50px;
    width: 30px;
}
2020-07-22