小编典典

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

reactjs

我处在需要进行dom节点大小计算(呈现的DOM节点的top,bottom和size属性)的情况下

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

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

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

这工作正常,但我有点担心性能,并会做出最佳做法。很多地方都在谈论使用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节点以获得引用即可,这对我来说并不正确。

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


阅读 343

收藏
2020-07-22

共1个答案

小编典典

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

2020-07-22