React中无法使用本地图片报401未授权错误,该如何解决?
React项目中正确加载本地图片的方法(解决401未授权错误)
你直接使用/src/images/backgroundImage.jpg作为图片路径是错误的——React项目构建后,src目录不会被打包到生产环境中,浏览器无法直接访问这个路径,这就是你遇到401错误的核心原因。以下是几种正确的本地图片加载方式:
1. 导入图片资源(推荐)
通过ES模块导入图片,构建工具会自动处理资源路径,生成正确的打包后路径:
import React from 'react' // 根据ProfilePage.js的位置调整相对路径,比如组件在src/components下就用../images/... import backgroundImage from './images/backgroundImage.jpg' export default function ProfilePage() { return ( <div> <div className='bg-slate-500 rounded-3xl text-center items-center'> <img className='w-full h-16' src={backgroundImage} alt='背景图' /> </div> </div> ) }
2. 将图片放入public目录
把图片放到项目根目录的public文件夹下,浏览器可以直接通过根路径访问:
- 步骤:在
public下新建images文件夹,将backgroundImage.jpg放入其中 - 组件中使用:
import React from 'react' export default function ProfilePage() { return ( <div> <div className='bg-slate-500 rounded-3xl text-center items-center'> <img className='w-full h-16' src='/images/backgroundImage.jpg' alt='背景图' /> </div> </div> ) }
3. 动态加载(适合动态场景)
如果需要动态切换图片,可以使用require加载:
import React from 'react' export default function ProfilePage() { const backgroundImage = require('./images/backgroundImage.jpg').default return ( <div> <div className='bg-slate-500 rounded-3xl text-center items-center'> <img className='w-full h-16' src={backgroundImage} alt='背景图' /> </div> </div> ) }
内容的提问来源于stack exchange,提问作者Kadir Özer Öztürk
相关产品推荐
相关产品推荐

