使用ReactJS时使用ref和document.getElementById等有什么区别? [英] What is the difference with using ref and document.getElementById, ect when using ReactJS?

查看:86
本文介绍了使用ReactJS时使用ref和document.getElementById等有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用之间有什么区别/优点/缺点:

What is the difference/advantages/disadvantages between using:

  React.findDOMNode(this.refs.elementReferenceName)

  document.getElementById(elementId)

什么时候使用 ReactJS?

when using ReactJS?

推荐答案

使用 React.findDOMNode 的主要优点和原因是它保持在 React 范式内,因为你传递给它一个组件——- 在大多数情况下,您正在处理 React 组件(处理生命周期函数或调用在组件描述符中实现的函数).

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

依赖 DOM 元素中的 id 会破坏 React 中的封装,因为它不使用 id.

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

话虽如此,这取决于您和您的特定应用的需求,以确定最适合使用哪个.与其他 React 函数一样,你必须小心,因为在错误的时间调用 React.findDOMNode 会引发异常.OTOH,如果组件被卸载,document.getElementById 不会抛出异常;但如果该 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 component is not mounted) will raise an exception. OTOH, document.getElementById won't throw an exception if the component is unmounted; but it could return the wrong element if multiple elements exist with that id.

如果你还没有找到,这里是 findDOMNode 的文档.

另外,这里是 findDOMNode 的实现

这篇关于使用ReactJS时使用ref和document.getElementById等有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆