最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the difference with using ref and document.getElementById, ect when using ReactJS? - Stack Overflow

programmeradmin2浏览0评论

What is the difference/advantages/disadvantages between using:

  React.findDOMNode(this.refs.elementReferenceName)

and

  document.getElementById(elementId)

when using ReactJS?

What is the difference/advantages/disadvantages between using:

  React.findDOMNode(this.refs.elementReferenceName)

and

  document.getElementById(elementId)

when using ReactJS?

Share Improve this question edited Mar 28, 2018 at 16:16 Joseph Quinsey 9,97210 gold badges56 silver badges80 bronze badges asked Aug 11, 2015 at 17:43 esanz91esanz91 8932 gold badges12 silver badges24 bronze badges 3
  • 1 findDOMNode (in normal circumstances) 1) make some checks and fails in a normal way if those fail; 2) fills out the internal cache (nodeCache) object. getElementById, apparently, doesn't do any of those - it just returns null if nothing's found. – raina77ow Commented Aug 11, 2015 at 17:56
  • This is just a note not answer: findDOMNode() only works on mounted ponents (that is, ponents that have been placed in the DOM). If you try to call this on a ponent that has not been mounted yet (like calling findDOMNode() in render() on a ponent that has yet to be created) an exception will be thrown. – anam Commented Aug 11, 2015 at 17:58
  • It lets you find the Dom node by element reference instead of id. What if your ponent has no classes or ids, or it does but you are unaware of them in current context? – Mike Driver Commented Aug 11, 2015 at 18:41
Add a ment  | 

1 Answer 1

Reset to default 6

The main advantage and reason to use React.findDOMNode is that it stays within the React paradigm, since you pass it a ponent--And in most cases you are dealing with React ponents (either handling a lifecycle function or calling a function that is implemented in the ponent descriptor).

Relying on the id in a DOM element breaks encapsulation in React because it doesn't use id.

That being said, it is up to you and your specific app's needs to determine which is best to use. As with other React functions, you do have to be careful because the calling React.findDOMNode at the wrong time (in render or if the ponent is not mounted) will raise an exception. OTOH, document.getElementById won't throw an exception if the ponent is unmounted; but it could return the wrong element if multiple elements exist with that id.

If you haven't yet found it, here is documentation for findDOMNode.

Also, here is the implementation of findDOMNode

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论