如何在 React 中引用本地图像? [英] How do I reference a local image in React?
问题描述
如何从本地目录加载图像并将其包含在 reactjs img src
标签中?
How can I load image from local directory and include it in reactjs img src
tag?
我在与组件相同的文件夹中有一个名为 one.jpeg
的图像,我尝试了 <img src="one.jpeg"/>
和<img src={"one.jpeg"}/>
在我的 render
函数中,但图像不显示.此外,我无权访问 webpack config
文件,因为该项目是使用官方 create-react-app
命令行工具创建的.
I have an image called one.jpeg
inside the same folder as my component and I tried both <img src="one.jpeg" />
and <img src={"one.jpeg"} />
inside my render
function but the image does not show up. Also, I do not have access to webpack config
file since the project is created with the official create-react-app
command line util.
更新:如果我首先使用 import img from './one.jpeg'
导入图像并在 img src={img}
中使用它,这会起作用,但是我有很多图像文件要导入,因此,我想以 img src={'image_name.jpeg'}
的形式使用它们.
Update: This works if I first import the image with import img from './one.jpeg'
and use it inside img src={img}
, but I have so many image files to import and therefore, I want to use them in the form, img src={'image_name.jpeg'}
.
推荐答案
首先将 src 包裹在 {}
First of all wrap the src in {}
那么如果使用Webpack;代替:<img src={"./logo.jpeg"}/>
Then if using Webpack;
Instead of:
<img src={"./logo.jpeg"} />
您可能需要使用 require:
You may need to use require:
另一种选择是首先导入图像:
Another option would be to first import the image as such:
从'./logo.jpeg'导入logo;//带导入
或...
const logo = require('./logo.jpeg);//带有要求
然后插入...
我建议您使用此选项,尤其是如果您要重复使用图像源.
I'd recommend this option especially if you're reusing the image source.
这篇关于如何在 React 中引用本地图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!