[英]Why does my img show up when I hardcode the src URL, but not when I assign it programmatically?
I'm creating a practice React app, and am using Firebase Storage to pull an image from my Firebase Storage bucket and show it on the website. 我正在创建一个练习React应用程序,并使用Firebase存储从我的Firebase存储桶中提取图像并在网站上显示。 The image, however, does not appear, despite the fact that the image URL is properly assigned to 's src. 但是,尽管图像URL已正确分配给src,但图像不会出现。 However, when I copy/paste the image URL directly into the src in JSX, everything shows up and works fine. 但是,当我将图像URL直接复制/粘贴到JSX中的src时,一切都会显示并正常工作。
My console.log() message shows the correct image URL is received before rendering. 我的console.log()消息显示在呈现之前接收到正确的图像URL。 Also, after the site has finished loading, running document.getElementsByClassName('Image').src in the developer tools console also shows the correct image URL. 此外,在网站加载完成后,在开发人员工具控制台中运行document.getElementsByClassName('Image')。src也会显示正确的图像URL。 When I hardcode the image URL into the src then everything works fine and the image displays. 当我将图像URL硬编码到src中时,一切正常,图像显示。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {url: ''};
let storage = firebase.storage();
let gsReference = storage.ref('blue.png');
gsReference.getDownloadURL().then(url=>
{
console.log("received URL: ", url);
this.setState({url: url})
}
);
}
render() {
document.getElementsByClassName('Image').src = this.state.url;
console.log("img URL: ", document.getElementsByClassName('Image').src);
return (
<img src="" className='Image' />
);
}
}
Try this to see if it work for you 试试这个,看看它是否适合你
<img src={this.state.url} className="Image" />
Also set image src using document query is not a best practise 使用文档查询设置图像src也不是最佳实践
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.