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

IT技术 javascript reactjs ecmascript-6 jsx create-react-app
2021-05-23 04:09:31

我无法加载某些背景图像。我对最初的 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并且效果很好。

应用程序.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')
);

应用程序.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.pngasimport 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

3个回答

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

应用程序.css

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

我的问题特别是我没有background-size: 30px;定义。谢谢你。

在 package.json 中添加主页以在任何 apache 服务器中运行构建

{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "homepage": "http://{servername}/{foldername}/",

}

然后使用创建内置react

  1. npm run build
  2. npm install -g serve
  3. serve -s build
  4. 复制构建文件夹并粘贴到服务器中,如 xampp/htdocs 并点击 url