2017-09-01 290 views
1

我得到了TypeError錯誤:嘗試獲取dom節點的offsetHeight時,無法讀取未定義的 屬性'offsetHeight'。componentDidMount獲取DOM節點出錯

componentDidMount() { 
     setTimeout(function(){ 
      console.log(this.contentBody.offsetHeight) 
     },1000) 
    } 

我懷疑這是我的異步,其中ref尚未設置。我的渲染方法是這樣的

<div ref={elem => this.contentBody = elem} className="content-body" dangerouslySetInnerHTML={createMarkupFromReferenceContent()} /> 

我想在這裏https://codesandbox.io/s/j46o2656vy創建一個非AJAX的演示和它的工作。這就是爲什麼我嘗試setTimeout黑客之上,但沒有運氣。任何線索如何解決這個問題?

+0

其在[如何訪問正確的\'這\'回調裏面?](HTTPS的setTimeout函數 –

+1

可能的複製具有約束力的問題: //stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) –

回答

0

您必須將this綁定到setTimeout回調函數。就像這樣:

componentDidMount() { 
 
     setTimeout(function(){ 
 
      console.log(this.contentBody.offsetHeight) 
 
     },1000).bind(this); 
 
    }

0

this reffers到最近的範圍,所以當你使用它的回調函數this點的回調函數,而不是你的對象。

在EcmaScript2015這可以通過使用箭頭功能是固定的:

componentDidMount() { 
    setTimeout(()=>{ 
     console.log(this.contentBody.offsetHeight) 
    },1000) 
} 

但這種語法不是在舊的瀏覽器支持(IE特別)

但是如果你需要跨瀏覽器支持只需使用一個變量:

componentDidMount() { 
    var self = this; 
    setTimeout(function(){ 
     console.log(self.contentBody.offsetHeight); 
    },1000) 
}