React-bootstrap 样式在完成 api 调用之前出现
React-bootstrap styling showing up before finished api call
我正在 React 中制作一个小型应用程序,它使用 Axios 获取随机图像。我正在使用 React-bootstrap 来设置图像样式,但是在图像加载完成之前会显示一个小白框半秒。我该如何解决?
这是我的代码:
import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Image, Button } from 'react-bootstrap';
const ROOT_URL = 'myurl'
export default class WhatDog extends Component {
constructor(props){
super(props);
this.state = { randomImg: '' };
}
componentDidMount(){
axios.get(ROOT_URL)
.then(res => {
const data = res.data.message
this.setState({ randomImg: data })
})
}
renderImage(){
return(
<div>
<Image src={this.state.randomImg} className="img" thumbnail/>
<Link to="/">
<Button bsStyle="danger" bsSize="large">Go back</Button>
</Link>
</div>
)
}
render() {
return (
<div className="App">
{
(this.state.randomImg === '')
? <div>
<h1>Loading...</h1>
</div>
: <div>
{this.renderImage()}
</div>
}
</div>
);
}
}
浏览器会触发 onLoad
事件,在图像生成后,你给它命名.. loaded
所以在那之前,将 visibility
设置为隐藏.. NOT display: none
!因为 display: none
也会阻止加载。
解决方案可能看起来像这样
<Image
src={this.state.randomImg}
style={!this.state.imgVisible ? {visibility: 'hidden'} : {}}
onLoad={() => this.setState({ imgVisible: true })}
/>
注意:这是使用内联样式和箭头函数,这不是最好的,但为了演示的简单性,它已经足够了,你也可以用 className 代替,这取决于你 ;)
你明白了...
我正在 React 中制作一个小型应用程序,它使用 Axios 获取随机图像。我正在使用 React-bootstrap 来设置图像样式,但是在图像加载完成之前会显示一个小白框半秒。我该如何解决?
这是我的代码:
import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { Image, Button } from 'react-bootstrap';
const ROOT_URL = 'myurl'
export default class WhatDog extends Component {
constructor(props){
super(props);
this.state = { randomImg: '' };
}
componentDidMount(){
axios.get(ROOT_URL)
.then(res => {
const data = res.data.message
this.setState({ randomImg: data })
})
}
renderImage(){
return(
<div>
<Image src={this.state.randomImg} className="img" thumbnail/>
<Link to="/">
<Button bsStyle="danger" bsSize="large">Go back</Button>
</Link>
</div>
)
}
render() {
return (
<div className="App">
{
(this.state.randomImg === '')
? <div>
<h1>Loading...</h1>
</div>
: <div>
{this.renderImage()}
</div>
}
</div>
);
}
}
浏览器会触发 onLoad
事件,在图像生成后,你给它命名.. loaded
所以在那之前,将 visibility
设置为隐藏.. NOT display: none
!因为 display: none
也会阻止加载。
解决方案可能看起来像这样
<Image
src={this.state.randomImg}
style={!this.state.imgVisible ? {visibility: 'hidden'} : {}}
onLoad={() => this.setState({ imgVisible: true })}
/>
注意:这是使用内联样式和箭头函数,这不是最好的,但为了演示的简单性,它已经足够了,你也可以用 className 代替,这取决于你 ;)
你明白了...