【问题标题】:Javascript: Error: Cannot find module '../data/icons/table.png'Javascript:错误:找不到模块'../data/icons/table.png'
【发布时间】:2018-06-22 03:21:50
【问题描述】:

我正在尝试将图像的路径传递给 react 中的子组件,然后将该路径作为子组件中的源属性提供。当我对子路径中的路径进行硬编码时,它可以工作,但是当我使用模板文字时,它不会。 下面是代码sn-p。我无法理解为什么模板文字不起作用

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>
    )
}}

【问题讨论】:

  • 可能不是解决方案,但&lt;img src={require(this.props.icon)} /&gt; 有效吗?
  • 谢谢亚历克斯,但我已经尝试过了,不起作用...
  • 如果this.props.icon已经是一个字符串,你为什么要包装它?
  • 它是一个字符串,但是作为props传递,在this.props.icon中,但是正如你在上面的评论中看到的,&lt;img src={require(this.props.icon)} /&gt;不起作用
  • 是的,Jared,但这只是为图像标签提供路径属性,实际导入在哪里?

标签: javascript node.js reactjs template-literals


【解决方案1】:

如果您以与 API 模块相同的方式使用捆绑器(如 webpack 或 yarn),则可以像模块一样加载图像。

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>
    )
}
}

【讨论】:

  • 这不是 ES 6 的导入,而是 webpack 的东西。仅在使用 webpack 时才有效(例如使用 create-react-app)。
  • 另请注意,虽然这在可能的情况下是首选,但在这种情况下,您不能使用它(至少不是您编写它的方式),因为图标的路径作为道具(例如它是动态的)。
猜你喜欢
  • 2018-11-04
  • 2022-11-03
  • 2022-01-20
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
相关资源
最近更新 更多