【发布时间】:2026-02-08 11:55:02
【问题描述】:
我无法加载一些背景图片。我对最初的 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.png 导入为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.jsx 和Footer.css
【问题讨论】:
-
您可以将鼠标悬停在类检查器中的图像 src 上并查看图像预览?
-
@4m1r 是的,我可以,我无法用我的屏幕截图捕捉到,但是当我将鼠标悬停在导入图像和背景图像的路径时,chrome 正在显示图像
-
你能提出问题吗?我会尽量记住回复这个问题,但如果你可以在 Create React App repo 中提交一个问题,这样它就会在那里可见,我会在下次打开问题跟踪器时看到它。
标签: javascript reactjs ecmascript-6 jsx create-react-app