Webpack需要React组件中的动态图像

Ter*_*how 5 image reactjs webpack

我正在使用React和Webpack.

我有一个React组件,它采用一个url并显示图像.

由于React在运行之前不会知道图像网址,因此webpack仍然可以"需要"图像网址吗?

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>
        )

    }
}
Run Code Online (Sandbox Code Playgroud)

作为参考,我的图片位于:

src/assets/images

我的网站正在建设中 dist

jum*_*oel 0

您可以使用import()动态加载图像。然后,您可以在 中执行类似以下操作componentDidMount

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

然后,在您的render- 函数中,您可以渲染占位符图像,例如透明 gif,直到this.state.image包含有效的内容。

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

    return <img src={imageSource} />;
}
Run Code Online (Sandbox Code Playgroud)