findDOMNode vs getElementById for plain DOM elements

强颜欢笑 提交于 2019-12-21 20:59:39

问题


I'm not quite sure there's a real answer to this question but I was wondering if it's better to find regular DOM elements in a React app by using

a. refs and ReactDOM.findDOMNode

or

b. plain old document.getElementById


回答1:


I would prefer the pattern of refs because it would encourage you not to add IDs to elements and therefore allow you to use multiple instances of a react component on a single page. The ref feature in react will get you the element rendered by that specific instance of the component, and not an element from any duplicate renderings of it.




回答2:


I don't really know what you're asking. If you're asking in terms of speed, getElementById() is O(1) in modern browsers. However, using DOM methods like that have the disadvantage of piercing the abstraction React provides.




回答3:


You created multiple objects with the same ID. When any of the components asks for the element with ID myInput, the browser hands back the first one

https://www.andrewhfarmer.com/use-refs-not-ids/



来源:https://stackoverflow.com/questions/36415198/finddomnode-vs-getelementbyid-for-plain-dom-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!