2017-04-16 84 views
5

我在這裏我想作一些DOM節點的大小計算(頂部,底部和大小等屬性渲染DOM節點)我應該使用ref還是findDOMNode來獲取元素的root dom節點?

我在做什麼,現在的情況下,對componentDidUpdate方法是調用findDOMNode對此:

componentDidUpdate() { 
     var node = ReactDOM.findDOMNode(this); 

     this.elementBox = node.getBoundingClientRect(); 
     this.elementHeight = node.clientHeight; 
     // Make calculations and stuff 
} 

這工作正常,但我有點擔心性能和反應最佳實踐。幾個地方談到使用ref屬性而不是findDOMNode,但所有這些都是爲了子DOM元素,在我的情況下我只想要我的組件的根DOM節點。

使用裁判可能看起來像這樣的選擇:

render(){ 
    return (
      <section // container 
       ref={(n) => this.node = n}> 
       // Stuff 
      </section> 
} 
componentDidUpdate() { 

     this.elementBox = this.node.getBoundingClientRect(); 
     this.elementHeight = this.node.clientHeight; 
     // Make calculations and stuff 
} 

說實話,附加裁判回調到我的根DOM節點只是爲了得到它的參考並不覺得正確的給我。

什麼被認爲是這種情況下的最佳做法?哪一個有更好的表現?

回答

1

如果我參考文檔(https://facebook.github.io/react/docs/react-dom.html#finddomnode),findDOMNode似乎是一個比真正的選擇更多的技巧。裁判似乎是最好的選擇。 doc執行您在此處提供的相同草稿(使用ref={(n) => this.node = n}

+1

再次閱讀我剛剛找到的文檔:>使用ref回調只是爲類設置屬性是訪問DOM元素的常見模式。首選的方法是像上例中那樣在ref回調中設置屬性。 – Danielo515

+0

順便說一句,我不知道你是否注意到,但JS標準我抱怨'{(n)=> this.node = n}'說「箭頭函數不應該返回賦值。」我想知道它是否合法投訴 – revelt