如何在React中引用本地图像?

reactjs React.js

西里宝儿Harry

2020-03-11

如何从本地目录加载图像并将其包含在reactjs img src标记中?

one.jpeg在与组件相同的文件夹中有一个名为的图像,<img src="one.jpeg" />并且<img src={"one.jpeg"} />render函数中都尝试了这两个图像,但该图像未显示。另外,webpack config由于该项目是使用官方create-react-app命令行util 创建的,因此我无权访问文件

更新:如果我首先导入图像import img from './one.jpeg'并在内部使用它img src={img}则此方法有效,但是我要导入的图像文件太多,因此,我想以形式使用它们img src={'image_name.jpeg'}

第745篇《如何在React中引用本地图像?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
LNear 2020.03.11

As some mentioned in the comments, you can put the images in the public folder. This is also explained in the docs of Create-React-App: https://create-react-app.dev/docs/using-the-public-folder/

古一达蒙 2020.03.11

内部公共文件夹中创建的资产文件夹,将映像路径相应。

<img className="img-fluid" 
     src={`${process.env.PUBLIC_URL}/assets/images/uc-white.png`} 
     alt="logo"/>

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android