【问题标题】:Should I use ref or findDOMNode to get react root dom node of an element?我应该使用 ref 还是 findDOMNode 来获取元素的根 dom 节点?
【发布时间】:2017-04-16 09:44:04
【问题描述】:

我想进行一些 dom 节点大小计算(渲染的 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 节点。

使用 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 节点只是为了获取它的引用对我来说并不正确。

在这种情况下,什么被认为是最佳实践?哪个性能更好?

【问题讨论】:

  • 遗憾的是,没有一个框架似乎已经适应了这种 ref 处理,并且即使在给定 refs 的情况下也默认为 findDOMNode。

标签: javascript reactjs dom react-dom


【解决方案1】:

如果我参考文档 (https://facebook.github.io/react/docs/react-dom.html#finddomnode),findDOMNode 似乎更像是一种技巧而不是真正的选择。 ref 似乎是最好的选择。 doc 实现了您在此处给出的相同草案(使用 ref={(n) =&gt; this.node = n}

【讨论】:

  • 再次阅读我刚刚找到的文档: >使用 ref 回调来设置类的属性是访问 DOM 元素的常见模式。首选方法是像上面的示例一样在 ref 回调中设置属性。
  • 顺便说一句,我不知道你是否注意到了,但是我所使用的 JS Standard 抱怨 {(n) =&gt; this.node = n} 说“箭头函数不应该返回赋值”。我想知道这是不是合法的投诉
  • @revelt 它不会导致运行时错误,但它实际上意味着您不应该返回作业。轻松修复:{(n) =&gt; { this.node = n}}
猜你喜欢
  • 2021-05-29
  • 2021-12-06
  • 2015-06-16
  • 2019-12-14
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多