我应该使用 ref 还是 findDOMNode 来获取元素的 react root dom 节点?

Should I use ref or findDOMNode to get react root dom node of an element?

我想进行一些 dom 节点大小计算(呈现的 DOM 节点的顶部、底部和大小属性)

我现在正在做的,在 componentDidUpdate 方法上调用 findDOMNode on this:

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

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

这工作正常,但我有点担心性能和 React 最佳实践。有几个地方谈到使用 ref 属性 而不是 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
}

老实说,将 ref 回调附加到我的根 dom 节点只是为了获取它的引用对我来说并不正确。

这种情况下的最佳做法是什么?哪个性能更好?

如果我参考文档(https://facebook.github.io/react/docs/react-dom.html#finddomnode), findDOMNode seems to be more a trick than a real option. The ref seems to be the best option. The doc 实现了您在此处给出的相同草案(带有 ref={(n) => this.node = n}