2017-08-25 57 views
1

我正在React中製作一個小應用程序,使用Axios獲取隨機圖像。我正在使用React-bootstrap來設置圖像的樣式,但是在圖像加載完成之前,會顯示一個半小時的白色框。我該如何解決這個問題?在完成api調用之前顯示的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> 
    ); 
    } 
} 
+0

你沒有看到** Loading ... **? –

+0

我看到加載,但我也看到它下面的小空白框。 – FakeEmpire

+0

圖像需要一些時間,直到它實際上完成由瀏覽器加載。 – webdeb

回答

0

瀏覽器將觸發onLoad事件,圖像已被後,你的名字.. loaded所以在這之前,設置visibility隱藏..不display: none!因爲display: none也會阻止加載。

的解決方案可能是這個樣子

<Image 
    src={this.state.randomImg} 
    style={!this.state.imgVisible ? {visibility: 'hidden'} : {}} 
    onLoad={() => this.setState({ imgVisible: true })} 
/> 

注:這是使用內聯樣式和箭頭的功能,這是不是最好的,但對於演示的簡單的話,你也可以你的className代替,它取決於你;)

你有想法...

+0

它工作正常!我只是改變了「風格」到「風格」。謝謝,朋友。 ;) – FakeEmpire

+1

Aa,gotcha,謝謝,我會更新它。 – webdeb

+1

也注意到,當你改變圖像時,你必須將'imgVisible'再次設置爲'false' – webdeb

相關問題