我应该使用ref或findDOMNode来获取元素的根节点吗?

Dan*_*515 16 javascript dom reactjs react-dom

我正处于一种情况,我想做一些dom节点大小计算(渲染的DOM节点的顶部,底部和大小属性)

我现在正在做的,componentDidUpdate方法是调用findDOMNode:

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

        this.elementBox = node.getBoundingClientRect();
        this.elementHeight = node.clientHeight;
        // Make calculations and stuff
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我有点担心性能,并做出最佳实践.有几个地方讨论使用refproperty而不是findDOMNode,但是所有这些都是针对子dom元素的,在我的情况下我只想要我的组件的根DOM节点.

使用ref的替代方案可能如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

老实说,将ref回调附加到我的根dom节点只是为了得到它的引用对我来说感觉不对.

什么被认为是这种情况下的最佳做法?哪一个有更好的表现?

soy*_*wod 9

如果我参考doc(https://facebook.github.io/react/docs/react-dom.html#finddomnode),findDOMNode似乎更像是一个技巧而不是真正的选择.裁判似乎是最好的选择.该文档实现了您在此处给出的相同草稿(随附ref={(n) => this.node = n})