Javascript 我应该使用 ref 还是 findDOMNode 来获取元素的反应根 dom 节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43435881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I use ref or findDOMNode to get react root dom node of an element?
提问by Danielo515
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)
我想进行一些 dom 节点大小计算(渲染的 DOM 节点的顶部、底部和大小属性)
What I'm doing right now, on the componentDidUpdatemethod is to call findDOMNode on this:
我现在正在做的componentDidUpdate方法是在这个方法上调用 findDOMNode:
componentDidUpdate() {
var node = ReactDOM.findDOMNode(this);
this.elementBox = node.getBoundingClientRect();
this.elementHeight = node.clientHeight;
// Make calculations and stuff
}
This is working fine, but I'm a bit worried about performance, and react best practices. Several places talks about using refproperty 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属性而不是 findDOMNode,但所有这些都是针对子 dom 元素的,在我的情况下,我只想要组件的根 DOM 节点。
The alternative using ref may look like this:
使用 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
}
To be honest, attaching a ref callback to my root dom node just to get it's reference does not feel correct to me.
老实说,将 ref 回调附加到我的根 dom 节点只是为了获取它的引用对我来说并不正确。
What is considered the best practice on this case ? Which one has better performance ?
在这种情况下,什么被认为是最佳实践?哪个性能更好?
采纳答案by soywod
If I refer to the doc (https://facebook.github.io/react/docs/react-dom.html#finddomnode), findDOMNodeseems to be more a trick than a real option. The ref seems to be the best option. The docimplements the same draft you gave here (with the ref={(n) => this.node = n})
如果我参考文档(https://facebook.github.io/react/docs/react-dom.html#finddomnode),findDOMNode似乎更像是一种技巧而不是真正的选择。ref 似乎是最好的选择。该文档实现了您在此处提供的相同草案(带有ref={(n) => this.node = n})

