React中require无法读取对象内图片路径的问题及解决方法
问题原因与解决方案
问题原因
React项目常用的打包工具(比如Webpack)会在构建阶段做静态代码分析,require()函数的参数必须是静态字符串,工具才能提前识别要打包的资源路径。当你用动态变量tech.image作为require()的参数时,构建工具无法在编译期确定具体要加载哪个图片,也就不会把这些图片加入打包资源列表,运行时自然找不到对应的模块。
而直接写require("../Utils/C.png")时,路径是明确的静态字符串,工具能提前定位到图片并打包,所以能正常渲染。
解决方法
方法1:修改数组,提前用require加载图片
直接在techStack数组的image字段中使用require()引入图片,让构建工具静态识别路径:
let techStack = [ { name: "C", image: require("../Utils/C.png"), rating: 4, }, { name: "Java", image: require("../Utils/Java.png"), rating: 3.5, }, { name: "Python", image: require("../Utils/Python.png"), rating: 3, }, { name: "React Js", image: require("../Utils/React.png"), rating: 3.5, }, { name: "Bootstrap", image: require("../Utils/Bootstrap.svg"), rating: 3.5, }, { name: "Node.Js", image: require("../Utils/Node.png"), rating: 3, }, { name: "Flask", image: require("../Utils/Flask.png"), rating: 3, }, { name: "MySql", image: require("../Utils/SQL.png"), rating: 4, }, ]
然后JSX中直接使用src={tech.image}即可,无需再嵌套require():
<img src={tech.image} alt={tech.name} style={{ marginBottom: "2%" }} width={sizeBreak ? "50px" : "100px"} />
方法2:将图片放到public目录
把图片移到项目根目录的public文件夹下(比如创建public/Utils目录存放图片),然后修改techStack的image字段为根相对路径:
let techStack = [ { name: "C", image: "/Utils/C.png", rating: 4, }, // 其他对象的image字段同理修改为"/Utils/xxx.png" ]
JSX中直接用src={tech.image},因为public目录下的资源会被直接部署,访问路径以根目录开头:
<img src={tech.image} alt={tech.name} style={{ marginBottom: "2%" }} width={sizeBreak ? "50px" : "100px"} />
方法3:使用import导入图片
先逐个import所有图片,再在数组中引用导入的变量:
import cImg from "../Utils/C.png"; import javaImg from "../Utils/Java.png"; import pythonImg from "../Utils/Python.png"; import reactImg from "../Utils/React.png"; import bootstrapImg from "../Utils/Bootstrap.svg"; import nodeImg from "../Utils/Node.png"; import flaskImg from "../Utils/Flask.png"; import mysqlImg from "../Utils/SQL.png"; let techStack = [ { name: "C", image: cImg, rating: 4, }, { name: "Java", image: javaImg, rating: 3.5, }, { name: "Python", image: pythonImg, rating: 3, }, { name: "React Js", image: reactImg, rating: 3.5, }, { name: "Bootstrap", image: bootstrapImg, rating: 3.5, }, { name: "Node.Js", image: nodeImg, rating: 3, }, { name: "Flask", image: flaskImg, rating: 3, }, { name: "MySql", image: mysqlImg, rating: 4, }, ]
JSX中同样直接使用src={tech.image}即可。
内容的提问来源于stack exchange,提问作者Kaustubh Paturi
相关产品推荐
相关产品推荐

