2017-09-01 284 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) 
}