React中如何通过JSON文件内的URL在img标签加载图片?
React中从JSON读取图片路径无法显示的解决方案
问题背景
正在开发简易博客页面,期望仅通过修改JSON文件即可新增博客内容,无需在JSX中手动导入图片,但尝试多种图片路径写法后均无法正常显示图片。
可行解决方案
方法1:将图片放入public目录(最简便)
这是最直接的方案,无需额外代码处理:
- 将图片移动到项目根目录的
public/assets/images/目录(不存在则创建) - 修改
Blogs.json中的图片路径为根相对路径:
[ { "id": 3, "name": "Blog Three", "desc": "A little description for blog three", "image": "/assets/images/Eli.png" }, { "id": 2, "name": "Blog Two", "desc": "A little description for blog two", "image": "/assets/images/Eli.png" }, { "id": 1, "name": "Blog One", "desc": "A little description for blog one", "image": "/assets/images/Eli.png" } ]
- 在
Blog.jsx中直接使用JSON里的路径:
<img src={blogs[0].image} alt={blogs[0].name} />
原理:public目录下的资源会被直接作为静态资源部署,无需构建工具处理,可通过根路径直接访问。新增博客时,只需将图片放入对应public路径,在JSON中添加条目即可。
方法2:Webpack项目用require.context预加载图片
若希望图片保留在src/assets目录下(如Create React App项目),可通过require.context批量导入图片:
- 修改
Blog.jsx代码:
import React from 'react' import BYFDC from '../global/BYFDC' import blogs from './Blogs.json' // 预加载src/assets/images下的所有png图片 const images = require.context('../assets/images', false, /\.png$/) // 根据图片文件名获取资源URL const getImageUrl = (fileName) => images(`./${fileName}`) function Blog() { return ( <div className='mt-[15vh]'> <div> <h1 className='text-4xl text-center items-center justify-center flex py-16 text-[#398492]'> YourCareerStrategy Blog </h1> {/* 遍历所有博客条目展示 */} {blogs.map(blog => ( <div key={blog.id} className='flex items-center justify-center'> <img src={getImageUrl(blog.image.split('/').pop())} alt={blog.name} /> <h1 className='text-center items-center justify-center flex py-16 '> {blog.name} </h1> </div> ))} <div> <BYFDC /> </div> </div> </div> ) } export default Blog
- 可简化
Blogs.json的image字段,直接写文件名(如"Eli.png"),这样getImageUrl可直接使用blog.image。
方法3:Vite项目用import.meta.glob动态导入
如果是Vite搭建的项目,使用import.meta.glob实现动态图片导入:
- 修改
Blog.jsx代码:
import React from 'react' import BYFDC from '../global/BYFDC' import blogs from './Blogs.json' // 批量导入src/assets/images下的所有png图片(eager: true表示立即加载) const imageModules = import.meta.glob('../assets/images/*.png', { eager: true }) // 根据JSON中的路径匹配对应图片资源 const getImageUrl = (path) => { const modulePath = path.replace('../../', '../') // 调整路径匹配glob规则 return imageModules[modulePath].default } function Blog() { return ( <div className='mt-[15vh]'> <div> <h1 className='text-4xl text-center items-center justify-center flex py-16 text-[#398492]'> YourCareerStrategy Blog </h1> {blogs.map(blog => ( <div key={blog.id} className='flex items-center justify-center'> <img src={getImageUrl(blog.image)} alt={blog.name} /> <h1 className='text-center items-center justify-center flex py-16 '> {blog.name} </h1> </div> ))} <div> <BYFDC /> </div> </div> </div> ) } export default Blog
内容的提问来源于stack exchange,提问作者Ahmad Nasser
相关产品推荐
相关产品推荐

