Javascript:错误:找不到模块'/数据/图标/表格.png';
我试图将图像的路径传递给react中的子组件,然后将该路径作为子组件中的源属性提供。当我在子对象中硬编码路径时,它工作,但当我使用模板文本时,它不工作。 下面是代码片段。我无法理解为什么模板文字不起作用Javascript:错误:找不到模块'/数据/图标/表格.png';,javascript,node.js,reactjs,template-literals,Javascript,Node.js,Reactjs,Template Literals,我试图将图像的路径传递给react中的子组件,然后将该路径作为子组件中的源属性提供。当我在子对象中硬编码路径时,它工作,但当我使用模板文本时,它不工作。 下面是代码片段。我无法理解为什么模板文字不起作用 import React, {Component} from 'react'; class MenuItem extends Component{ render(){ // the below 2 lines print exactly the same thing, i.e.,
import React, {Component} from 'react';
class MenuItem extends Component{
render(){
// the below 2 lines print exactly the same thing, i.e., string ../data/icons/table.png
console.log(typeof `${this.props.icon}`, `${this.props.icon}`);
console.log(typeof "../data/icons/table.png", "../data/icons/table.png");
return (
<div className = "sidemenu menu-item">
<img src={require("../data/icons/table.png")} /> //this works
<img src={require(`${this.props.icon}`)} /> //Error: Cannot find module '../data/icons/table.png'.
{this.props.name}
</div>
)
}}
import React,{Component}来自'React';
类MenuItem扩展组件{
render(){
//下面两行打印的内容完全相同,即string../data/icons/table.png
log(typeof`${this.props.icon}`、`${this.props.icon}`);
log(typeof“./data/icons/table.png”和“./data/icons/table.png”);
返回(
//这很有效
//错误:找不到模块“../data/icons/table.png”。
{this.props.name}
)
}}
如果您以与API模块相同的方式使用捆绑机(如网页包或纱线),则可以像模块一样加载图像
import React, {Component} from 'react';
import table from './data/icons/table.png';
class MenuItem extends Component{
render(){
return (
<div className = "sidemenu menu-item">
<img src={table} />
</div>
)
}
}
import React,{Component}来自'React';
从“./data/icons/table.png”导入表格;
类MenuItem扩展组件{
render(){
返回(
)
}
}
可能不是解决方案,但是
有效吗?谢谢Alex,但我已经尝试过了,不起作用…如果这个.props.icon
已经是一个字符串,为什么要包装它呢?它是一个字符串,但在这个.props.icon中作为一个道具传递,但正如您在上面的注释中看到的,
不起作用是的Jared,但这只是为图像标签提供路径属性,导入实际发生在哪里?这不是ES 6导入,而是一个网页包。仅在使用webpack(例如,与create react应用程序一起使用)时才有效。还请注意,虽然这是首选方法,但在这种情况下,您不能使用它(至少不是您编写它的方式),因为图标的路径作为道具传递给构造函数(例如,它是动态的)。