当前位置:   article > 正文

react虚拟dom原理_快速了解React及其虚拟DOM的工作原理

react 虚拟dom的工作原理

react虚拟dom原理

This is part of my “React for beginners” series on introducing React, its core features and best practices to follow. More articles are coming!
这是我的“初学者React”系列的一部分,该系列介绍了React,其核心功能和可遵循的最佳实践。 更多文章来了!

Next article >

下一篇文章>

Do you want to learn React without crawling the documentation (well written by the way)? You clicked on the right article.

您是否想在不爬行文档的情况下学习React(顺便说一下)? 您单击了正确的文章。

We will learn how to run React with a single HTML file and then expose ourselves to a first snippet.

我们将学习如何使用单个HTML文件运行React,然后将自己暴露给第一个片段。

By the end, you will be able to explain these concepts: props, functional component, JSX, and Virtual DOM.

最后,您将能够解释以下概念:道具,功能组件,JSX和虚拟DOM。

The goal is to make a watch which displays hours and minutes. React offers to architect our code with components. `Let’s create our watch component.

目的是制作一块显示小时和分钟的手表。 React提供了使用组件构建代码的方法。 `让我们创建手表组件。

  1. <!-- Skipping all HTML5 boilerplate -->
  2. <script src="https://unpkg.com/react@16.2.0/umd/react.development.js"></script>
  3. <script src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
  4. <!-- For JSX support (with babel) -->
  5. <script src="https://unpkg.com/babel-standalone@6.24.2/babel.min.js" charset="utf-8"></script>
  6. <div id="app"></div> <!-- React mounting point-->
  7. <script type="text/babel">
  8. class Watch extends React.Component {
  9. render() {
  10. return <div>{this.props.hours}:{this.props.minutes}</div>;
  11. }
  12. }
  13. ReactDOM.render(<Watch hours="9" minutes="15"/>, document.getElementById('app'));
  14. </script>

Ignore HTML boilerplate and script imports for dependencies (with unpkg, see React example). The few remaining lines are actually React code.

忽略依赖关系HTML样板文件和脚本导入(使用unpkg ,请参见React示例 )。 剩下的几行实际上是React代码。

First, define the Watch component and its template. Then mount React into the DOM and ask to render a watch.

首先,定义监视组件及其模板。 然后将React安装到DOM中并要求渲染手表。

将数据注入组件 (Inject data into the component)

Our watch is quite stupid, it displays the hours and minutes we provided to it.

我们的手表很傻,它显示了我们提供给它的小时和分钟。

You can try to play around and change the value for those properties (called props in React). It will always display what you asked for even if it’s not numbers.

您可以尝试修改这些属性的值(在React中称为props )。 即使不是数字,它也会始终显示您要的内容。

This kind of React component with only a render function are functional component. They have a more concise syntax compared to classes.

这种只有渲染功能的React组件是功能组件。 与类相比,它们的语法更简洁。

  1. const Watch = (props) =>
  2. <div>{props.hours}:{props.minutes}</div>;
  3. ReactDOM.render(<Watch hours="Hello" minutes="World"/>, document.getElementById('app'));

Props are only data passed to a component, generally by a surrounding component. The component uses props for business logic and rendering.

道具只是通常由周围组件传递到组件的数据。 该组件将道具用于业务逻辑和渲染。

But as soon as props do not belong to the component they are immutable. Thus, the component which provided the props is the only piece of code able to update props values.

但是,一旦道具不属于组件,它们就不会改变 。 因此,提供道具的组件是唯一能够更新道具值的代码。

Using props is pretty straightforward. Create a DOM node with your component name as the tag name. Then give it attributes named after props. Then the props will be available through this.props in the component.

使用道具非常简单。 使用您的组件名称作为标记名称创建一个DOM节点。 然后赋予它以道具命名的属性。 然后,可通过this.props中的this.props获得道具。

不带引号HTML呢? (What about unquoted HTML ?)

I was sure you will notice the unquoted HTML returned by the render function. This code is using JSX language, it’s a shorthand syntax to define HTML template in React components.

我确定您会注意到render函数返回的未引用HTML。 这段代码使用的是JSX 语言,这是在React组件中定义HTML模板的简写语法。

  1. // Equivalent to JSX: <Watch hours="9" minutes="15"/>
  2. React.createElement(Watch, {'hours': '9', 'minutes': '15'});

Now you may want to avoid JSX to define the component’s template. Actually, JSX looks like syntactic sugar.

现在,您可能要避免使用JSX定义组件的模板。 实际上,JSX看起来像语法糖

Take a look at the following snippet which shows both JSX and React syntax to build your opinion.

请看以下显示JSX和React语法的代码片段,以建立您的意见。

  1. // Using JS with React.createElement
  2. React.createElement('form', null,
  3. React.createElement('div', {'className': 'form-group'},
  4. React.createElement('label', {'htmlFor': 'email'}, 'Email address'),
  5. React.createElement('input', {'type': 'email', 'id': 'email', 'className': 'form-control'}),
  6. ),
  7. React.createElement('button', {'type': 'submit', 'className': 'btn btn-primary'}, 'Submit')
  8. )
  9. // Using JSX
  10. <form>
  11. <div className="form-group">
  12. <label htmlFor="email">Email address</label>
  13. <input type="email" id="email" className="form-control"/>
  14. </div>
  15. <button type="submit" className="btn btn-primary">Submit</button>
  16. </form>

虚拟DOM更进一步 (Going further with the Virtual DOM)

This last part is more complicated but very interesting. It will help you to understand how React is working under the hood.

最后一部分比较复杂,但非常有趣。 它将帮助您了解React在幕后的工作方式。

Updating elements on a webpage (a node in the DOM tree) involves using the DOM API. It will repaint the page but it can be slow (see this article for why).

更新网页(DOM树中的一个节点)上的元素需要使用DOM API。 它将重新绘制页面,但是速度可能很慢(有关原因,请参见本文 )。

Many frameworks such as React and Vue.js get around this problem. They come up with a solution called the Virtual DOM.

React和Vue.js等许多框架都可以解决此问题。 他们提出了一种称为虚拟DOM的解决方案。

  1. {
  2. "type":"div",
  3. "props":{ "className":"form-group" },
  4. "children":[
  5. {
  6. "type":"label",
  7. "props":{ "htmlFor":"email" },
  8. "children":[ "Email address"]
  9. },
  10. {
  11. "type":"input",
  12. "props":{ "type":"email", "id":"email", "className":"form-control"},
  13. "children":[]
  14. }
  15. ]
  16. }

The idea is simple. Reading and updating the DOM tree is very expensive. So make as few changes as possible and update as few nodes as possible.

这个想法很简单。 读取和更新DOM树非常昂贵。 因此,请进行尽可能少的更改并尽可能少地更新节点。

Reducing calls to DOM API involves keeping DOM tree representation in memory. Since we are talking about JavaScript frameworks, choosing JSON sounds legitimate.

减少对DOM API的调用涉及将DOM树表示形式保留在内存中。 由于我们在谈论JavaScript框架,因此选择JSON听起来很合理。

This approach immediately reflects changes in the Virtual DOM.

这种方法立即反映了虚拟DOM中的更改。

Besides, it gathers a few updates to apply later on the Real DOM at once (to avoid performance issues).

此外,它收集了一些更新,以便稍后立即应用于Real DOM(以避免性能问题)。

Do you remember React.createElement ? Actually, this function (called directly or through JSX) creates a new node in the Virtual DOM.

您还记得React.createElement吗? 实际上,此函数(直接调用或通过JSX调用)在虚拟DOM中创建一个新节点。

  1. // React.createElement naive implementation (using ES6 features)
  2. function createElement(type, props, ...children) {
  3. return { type, props, children };
  4. }

To apply updates, the Virtual DOM core feature comes into play, the reconciliation algorithm.

为了应用更新, 对帐算法是Virtual DOM核心功能。

Its job is to come up with the most optimized solution to resolve the difference between previous and current Virtual DOM state.

它的工作是提出最优化的解决方案,以解决以前和当前虚拟DOM状态之间的差异。

And then apply the new Virtual DOM to the real DOM.

然后将新的虚拟DOM应用于真实DOM。

进一步阅读 (Further readings)

This article goes far on React internal and Virtual DOM explanations. Still, it’s important to know a bit about how a framework works when using it.

本文对React内部和虚拟DOM的解释进行了深入介绍。 尽管如此,了解框架在使用时的工作原理还是很重要的。

If you want to learn how the Virtual DOM works in details, follow my reading recommendations. You can write your own Virtual DOM and learn about DOM rendering.

如果您想详细了解Virtual DOM的工作原理,请遵循我的阅读建议。 您可以编写自己的虚拟DOM并了解DOM渲染

How to write your own Virtual DOM‌‌

如何编写自己的虚拟DOM

There are two things you need to know to build your own Virtual DOM. You do not even need to dive into React’s source…

要构建自己的虚拟DOM,需要了解两件事。 您甚至不需要深入研究React的源代码……

Thank you for reading. Sorry if this is too technical for your first step in React. But I hope now you are aware of what props, functional component, JSX, and Virtual DOM are.

感谢您的阅读。 抱歉,这对于您在React的第一步来说太技术性了。 但是,我希望您现在知道什么是道具,功能组件,JSX和虚拟DOM。

If you found this article useful, please click on the ? button a few times to make others find the article and to show your support! ?

如果您发现本文有用,请单击“ ?”。 几次单击以使其他人找到该文章并表示您的支持!

Don’t forget to follow me to get notified of my upcoming articles ?

别忘了跟随我以获取有关我即将发表的文章的通知吗?

This is part of my “React for beginners” series on introducing React, its core features and best practices to follow.
这是我的“初学者React”系列的一部分,该系列介绍了React,其核心功能和可遵循的最佳实践。

Next article >

下一篇文章>

➥JavaScript (➥ JavaScript)
➥提示与技巧 (➥ Tips & tricks)

Originally published at www.linkedin.com on February 6, 2018.

最初于2018年2月6日发布在www.linkedin.com上。

翻译自: https://www.freecodecamp.org/news/a-quick-guide-to-learn-react-and-how-its-virtual-dom-works-c869d788cd44/

react虚拟dom原理

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/49759?site
推荐阅读
相关标签
  

闽ICP备14008679号