问题描述
我正处于一种情况,我想做一些dom节点大小计算(渲染的DOM节点的顶部,底部和大小属性)
I'm on a situation where I want to make some dom-node size calculations (top, bottom and size properties of the rendered DOM node)
我是什么现在正在做的,在 componentDidUpdate
方法是在这上面调用findDOMNode:
What I'm doing right now, on the componentDidUpdate
method is to call findDOMNode on this:
componentDidUpdate() {
var node = ReactDOM.findDOMNode(this);
this.elementBox = node.getBoundingClientRect();
this.elementHeight = node.clientHeight;
// Make calculations and stuff
}
这个工作正常,但是我有点担心性能,并做出最佳实践。有几个地方讨论使用 ref
属性而不是findDOMNode,但所有这些都是针对子dom元素的,在我的情况下我只想要我的组件的根DOM节点。
This is working fine, but I'm a bit worried about performance, and react best practices. Several places talks about using ref
property instead of findDOMNode, but all of them are for child dom elements, on my case I only want the root DOM node of my component.
使用ref的替代方案可能如下所示:
The alternative using ref may look like this:
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回调附加到我的root dom节点只是为了得到它的参考对我来说感觉不正确。
To be honest, attaching a ref callback to my root dom node just to get it's reference does not feel correct to me.
这个案例的最佳做法是什么?哪一个更好性能?
What is considered the best practice on this case ? Which one has better performance ?
推荐答案
如果我参考doc(),科幻ndDOMNode
似乎比真正的选择更具窍门。裁判似乎是最好的选择。 实现了您在此处提供的相同草稿(使用 ref = {(n)=> this.node = n}
)
If I refer to the doc (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 implements the same draft you gave here (with the ref={(n) => this.node = n}
)
这篇关于我应该使用ref或findDOMNode来获取元素的根节点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!