【发布时间】: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>
)
}}
【问题讨论】:
-
可能不是解决方案,但
<img src={require(this.props.icon)} />有效吗? -
谢谢亚历克斯,但我已经尝试过了,不起作用...
-
如果
this.props.icon已经是一个字符串,你为什么要包装它? -
它是一个字符串,但是作为props传递,在this.props.icon中,但是正如你在上面的评论中看到的,
<img src={require(this.props.icon)} />不起作用 -
是的,Jared,但这只是为图像标签提供路径属性,实际导入在哪里?
标签: javascript node.js reactjs template-literals