React JS中的条件渲染和图像路径 [英] Conditional rendering and image path in React JS
问题描述
我真的不了解一会儿.假设我有一个组件,可以有条件地渲染这样的数据:
I don't really understand one moment. Let's say I have a component which conditionally renders data like this:
<div>
{isLoading ? <img src="../pathname/img.jpg" alt="loading" /> : <Page />}
</div>
未以这种方式渲染图像,显示了一个损坏的文件图标.但是,如果我导入同一张图片,则效果很好:
Image is not rendered this way, shows a broken file icon. However, if I import the same image it works just fine:
import loadingImage from "../pathname/img.jpg"
<div>
{isLoading ? <img src={loadingImage} alt="loading" /> : <Page />}
</div>
我使用npm start
,我的编辑器是VS Code.您是否知道导入它的原因是什么,而不仅仅是路径src
中提供的路径名,即使路径相同也是如此?在第一个示例中,我提供的路径和文件名都是100%正确.
I use npm start
and my editor is VS Code. Do you know may be what is the reason to import it and not just simply provide a path name in src
even if path is the same? The path I provided and file name was 100% correct in the first example.
推荐答案
发生这种情况是因为您的图像可能不在public
文件夹中.
That happens because your image probably isn't inside public
folder.
您可以将资源添加到公用文件夹中,然后您就可以对其进行访问.
You can add assets to the public folder and then you will have access to it.
例如对于下面的代码,您需要一个pathname
文件夹,其中public
文件夹中包含img.jpg.
e.g. For the code below, you will need a pathname
folder with the img.jpg inside the public
folder.
<img src="../pathname/img.jpg" alt="loading" />
但是最好的方法是在JavaScript文件中使用导入. 这种机制有很多好处:
But the best way to do this is using import in JavaScript files. This mechanism provides a number of benefits:
- 缩小脚本和样式表并将其捆绑在一起,以避免 额外的网络请求.
- 文件包含在捆绑包中
- 缺少文件会导致编译错误,而不是404错误 用户.
- 结果文件名包含内容哈希,因此您无需担心 有关浏览器缓存其旧版本的信息.
- Scripts and stylesheets get minified and bundled together to avoid extra network requests.
- Files are included in the bundle
- Missing files cause compilation errors instead of 404 errors for your users.
- Result filenames include content hashes so you don’t need to worry about browsers caching their old versions.
使用import
,呈现页面时,您将在图像中看到类似以下内容:src="/static/media/img.xxxxx.jpg"
.那是因为使用import告诉webpack将文件包含在捆绑软件中.
With import
, when the page is rendered, you will see sometinhg like this in the image: src="/static/media/img.xxxxx.jpg"
. Thats because using import tells webpack to include that file in the bundle.
您可以在此处查看更多信息-添加图像-字体和文件,然后在此处使用-公共文件夹
You can check more here - adding-images-fonts-and-files and here using-the-public-folder
这篇关于React JS中的条件渲染和图像路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!