2016-01-04 115 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}/> 
 
     ) 
 
    } 
 
}