React子组件图像未通过传递道具加载

时间:2019-02-14 08:52:44

标签: javascript reactjs

我有一个父级和一个子级组件,其中父级通过一个图像路径以便被子级显示。 enter image description here

说:

/* Parent */
...
...
<Child imagePath={path /*This is coming from server*/} />
...

我在子组件中这样做:

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

这会引起恐慌,并说出给定的图像,例如“ my_image.jpg”不存在。

  

错误:找不到模块'/static/media/my_image.b05f9b9b.jpg'

当我以静态字符串传递图像路径时,一切都进行顺利。

为了不在render方法中使用require(....),我做了如下操作:

/* ---------- Child Component --------- */
state={myImage: null};

componentDidMount(){
   let img = require(this.props.imagePath);
   this.setState({myImage : img});       
}

render(){
   return(
    <div>
        <img alt="...." src={this.state.myImage} />
    </div>
 )
}

我再次遇到相同的错误。 我有什么失误吗?

1 个答案:

答案 0 :(得分:1)

显示<img>标签时,浏览器会自动处理加载,缓存和显示使用src属性指定的图像。

所以您要做的就是在<img src={this.props.imagePath} />中放入render