2016-01-04 65 views
5

动态图像。的WebPack要求我使用与的WebPack反应的阵营组件

我有一个阵营的组件,需要一个道具,其是一个URL并显示该图像。

由于React直到运行时才会知道图片url,webpack仍然可以'需要'图片url吗?

import React, {Component} from 'react' 

export default class Episode extends Component { 

    constructor(props){ 
     super(props) 
    } 

    render(){ 

     let imageStyle = {backgroundImage: 'url(' + this.props.episode.url +')'} 

    return (
      <div className="episode"> 
        <div className="image" style={imageStyle}> 
         <h2>{this.props.episode.category}</h2> 
        </div> 
       <h3>Episode {this.props.episode.number}</h3> 
      </div> 
     ) 

    } 
} 

仅供参考,我的图片位于:

src/assets/images

和我的WebPack正在建立dist

+0

是我认为的base64 URL数据?如果是这样做的重要组成部分,是你在哪里加载该数据,什么的WebPack装载机你使用它 –

+0

@DominicTobias它不是Base 64个数据。我通过轮询我的服务器来获取数据,以找出与用户当前正在查看的特定情节相关的图像URL –

+0

这可能有所帮助。 http://stackoverflow.com/questions/29421409/how-to-load-all-files-in-a-subdirectories-using-webpack-without-require-statemen –

回答

0

您可以使用import()动态加载图像。然后,你可以不喜欢在componentDidMount如下:

import('path/to/images/' + this.props.episode.url).then(function(image) { 
    this.setState({ image: image }); 
}).catch(function(err) { 
    // Do something 
}); 

在你render - 功能你就可以呈现一个占位符图像,例如a transparent gif,直到this.state.image中含有一种有效。

render() { 
    const imageSource = this.state.image 
     ? this.state.image 
     : "data:image/gif;base64,R0lGODlhAQABAAAAACw="; 

    return <img src={imageSource} />; 
} 
1

仅供参考,Jumoels答案几乎存在,但不能在componentWillMount中执行导入语句。

我对这个解决方案如下:

class YourComponent extends Component { 
 
    constructor(props){ 
 
     super(props); 
 
     
 
     this.state = { 
 
      image: "" 
 
     }; 
 
    } 
 

 
    componentWillMount(){ 
 
     this.state.image = require('../../public/assets/img/' + this.props.img); 
 
    } 
 

 
    render() { 
 
     return(
 
      <img src={this.state.image}/> 
 
     ) 
 
    } 
 
}