【发布时间】: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