我在无法加载某些背景图片时遇到困难。我对最初的 create react app 做了一些重大修改,我的文件夹结构现在如下所示:
注意:我省略了一些文件和文件夹,如果您需要更多请告诉我。
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 中的元素时,图像的路径似乎是正确的。当我将鼠标悬停在检查器样式选项卡中的图像路径上时,图像就会出现。
请注意,我导入的图像路径与背景图像的路径类似:
If I were to import the tree.png
as import tree from './images/tree.png';
and change my two <div>
elements to <img src={tree} role="presentation" className="trees__tree trees__tree--1" />
and <img src={tree} role="presentation" className="trees__tree trees__tree--2" />
the图片当然会加载。
我怎样才能让背景图像显示?我的应用程序中还有其他背景图片未加载,因此前面提到的创可贴对我没有帮助。我害怕弹出我的应用程序并弄乱配置。
我在构建应用程序时也遇到了同样的问题。
如果您需要查看更多源代码,可以在 https://github.com/studio174/ispellits 查看它,但请记住,我已简化此示例以隔离问题。我遇到的问题实际上是在 Footer.jsx
和 Footer.css
原文由 j_quelly 发布,翻译遵循 CC BY-SA 4.0 许可协议
该问题纯粹是
App.css
文件中 CSS 的问题:应用程序.css