Webpack需要React组件中的动态图像
发布时间:2020-12-15 20:20:51 所属栏目:百科 来源:网络整理
导读:我正在使用React和Webpack. 我有一个React组件,它采用一个url并显示图像. 由于React在运行之前不会知道图像网址,因此webpack仍然可以“需要”图像网址吗? import React,{Component} from 'react'export default class Episode extends Component { construc
我正在使用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> ) } } 作为参考,我的图片位于: SRC /资产/图片 而我的webpack正在建设中 解决方法
作为参考,Jumoels的回答几乎就在那里,但你不能在componentWillMount中做一个import语句.
我对此的解决方案如下: 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}/> ) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |