2016-07-15 25 views
2

我正在開發React應用程序並嘗試獲取DOM元素的計算樣式「scrollHeight」。爲什麼我無法在React componentDidMount中獲取DOMNode的樣式(scrollHeight)?

我把這個代碼在componentDidMount:

componentDidMount() { 

     // let _this = this; 
     // window.onload = function(){ 


     let imgFigureDOM = findDOMNode(_this.refs.imgFigure0), 
      imgW = imgFigureDOM.scrollWidth, 
      imgH = imgFigureDOM.scrollHeight; 
     // } 
    } 

但是,我不僅可以在Chrome browser.It獲得scrollHeight屬性的正確值似乎鉻不夠快渲染的DOMNode完全在findDOMNode執行時。

當我像上面那樣使用window.onload時,該值是正確的,但是當componentDidMount執行時不應該完全加載DOMNode嗎?

謝謝你耐心的回答!

+0

我並不感到驚訝,元素被附加到DOM是從他們不同的被完全呈現 –

回答

2

在渲染React組件時調用componentDidMount()。 React已呈現<img>標記,這並不意味着圖像已加載。

讓我們設置一些基本的定義來區分加載渲染:

  • 呈現

    :陣營已轉換虛擬DOM元素(render方法規定)爲真正的DOM元素,並將它們連接到DOM。

  • 已加載:圖像數據或其他遠程內容已完全下載(或未能下載)。

所以纔在onLoad和onError的事件處理程序添加到您的陣營<img>標籤,並遠離你去。 image-events

簡短的例子:

import React from 'react'; 

class ImageWithStatusText extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { imageStatus: null }; 
} 

handleImageLoaded(e){ 
    this.setState({ imageStatus: 'loaded' }); 
    console.log(e.target.scrollHeight); 
} 

handleImageErrored() { 
    this.setState({ imageStatus: 'failed to load' }); 
} 

render() { 
    return (
    <div> 
     <img 
     src={this.props.imageUrl} 
     onLoad={this.handleImageLoaded.bind(this)} 
     onError={this.handleImageErrored.bind(this)} 
     /> 
     {this.state.imageStatus} 
    </div> 
); 
} 
} 
export default ImageWithStatusText; 
+0

非常感謝您!我認爲渲染意味着負載是理所當然的。該示例有助於進一步理解:) – WebPansy

相關問題