简体   繁体   English

React 中的 DOM 与 Refs

[英]DOM vs Refs in React

What is the difference between using DOM vs Refs in React?在 React 中使用 DOM 和 Refs 有什么区别? I understand that we can use regular javascript DOM node selectors to target specific elements in react because react is javascript anyways, but you can also use refs to do the same thing.我知道我们可以使用常规的 javascript DOM 节点选择器来定位 react 中的特定元素,因为 react 无论如何都是 javascript,但您也可以使用 refs 来做同样的事情。 What are the benefits/disadvantages of using one vs the other?使用一种与另一种有什么好处/坏处?

它只是访问 DOM 节点或 React 元素的一种反应方式。

Refs provide a way to access DOM nodes or React elements created in the render method. Refs 提供了一种访问 DOM 节点或在 render 方法中创建的 React 元素的方法。 You can check the documentation for more informations.您可以查看文档以获取更多信息。

It's because of React, JSX, and the lifecycle pipeline.这是因为 React、JSX 和生命周期管道。 When you hear people refer to the React ecosystem, these are parts of that ecosystem.当你听到人们提到 React 生态系统时,这些都是该生态系统的一部分。 Refs make working within that ecosystem a little more smooth. Refs 使在该生态系统中的工作更加顺畅。

In React, you typically interact with elements when there is a data change, which causes our typical lifecycle events like mounting and unmounting.在 React 中,您通常会在数据发生更改时与元素进行交互,这会导致我们典型的生命周期事件,例如挂载和卸载。

DOM Selectors happens outside of that lifecycle, making what it returns unreliable, while refs happen within it. DOM 选择器发生在该生命周期之外,使其返回的内容不可靠,而 refs 发生在其中。 This ensures the object returned by the ref is an accurate representation of the current state of the virtual DOM.这确保了 ref 返回的 object 是虚拟 DOM 的当前 state 的准确表示。

More Info 更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM