2017-08-06 35 views
0

我给我的组件2道具src和ALT键,以便它可以显示像这样的图像:导入图像作出反应

<img src={require(this.props.src)} alt={this.props.alt} /> 

运行我的应用程序给了我这个错误

Error: Cannot find module "."

我试过图片网址,它是正确的,并且工作,当我提供需要道具时,应用程序就不想工作。

+0

你为什么需要?你不能只有'src = {this.props.src}'? – Dario

+0

不,webpack正在处理所有的文件。 –

+1

你不应该在运行时需要这样的文件。给它一个来自目标文件夹的绝对路径。 – Win

回答

0

如果您使用的是webpack,我会假设您使用的是webpack图片加载器。如果是这种情况,这意味着你正在将组件导入图像,可能使用了命名导入。在这种情况下,您可以将指定的导入作为通道传递给子组件,也可以直接在导入所在的组件上使用它。

// named import 
import landscape from "./img/landscape.jpg"; 
// child component 
import Child from "./components/child"; 

const Parent =() => 
    <div> 
    <Child src={landscape} /> 
    </div>; 


// then the child component could look like this 
const Child = (props) => 
    <div> 
    <img src={props.src} /> 
    </div>; 

如果不是这种情况,请提供有关的详细信息的WebPack是如何处理你的分量的图像。