Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Image 网页包需要在React组件中使用动态图像_Image_Reactjs_Webpack - Fatal编程技术网

Image 网页包需要在React组件中使用动态图像

Image 网页包需要在React组件中使用动态图像,image,reactjs,webpack,Image,Reactjs,Webpack,我正在使用React with Webpack 我有一个React组件,它接受一个作为url的道具并显示图像 由于React在运行时之前不会知道图像url,所以webpack是否仍然“需要”图像url import React, {Component} from 'react' export default class Episode extends Component { constructor(props){ super(props) } ren

我正在使用React with Webpack

我有一个React组件,它接受一个作为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>
        )

    }
}
import React,{Component}来自“React”
导出默认类扩展组件{
建造师(道具){
超级(道具)
}
render(){
让imageStyle={backgroundImage:'url('+this.props.插曲.url+')}
返回(
{this.props.eposion.category}
插曲{这个。道具。插曲号}
)
}
}
作为参考,我的图片位于:

src/assets/images

我的网页正在构建为
dist

,您可以使用它动态加载图像。然后,您可以在
componentDidMount
中执行以下操作:

import('path/to/images/' + this.props.episode.url).then(function(image) {
    this.setState({ image: image });
}).catch(function(err) {
    // Do something
});
例如,在
render
-函数中,您可以渲染占位符图像,直到
this.state.image
包含有效的内容

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

    return <img src={imageSource} />;
}
render(){
const imageSource=this.state.image
这是我的国家形象
:“数据:image/gif;base64,r0lgodlhaqabaaacw=”;
返回;
}

作为参考,Jumoels的答案几乎就在那里,但您不能在组件Willmount中执行导入语句

我的解决办法如下:

class YourComponent扩展组件{
建造师(道具){
超级(道具);
此.state={
图像:“
};
}
组件willmount(){
this.state.image=require('../../public/assets/img/'+this.props.img);
}
render(){
返回(
)
}

}
我接受的是url base64数据吗?如果是这样的话,重要的部分是你在哪里加载数据,以及你使用什么样的网页加载器it@DominicTobias它不是基本数据。我通过轮询服务器来获取数据,以找出与用户当前观看的特定剧集相关的图像url。这可能会有所帮助。