自学内容网 自学内容网

html,js,react三种方法编写helloworld理解virtual dom

学习任何一个新语言,好像都从helloworld开始。:)。

html helloworld

静态hello world

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <p>Hello World</p>
</body>
</html>

js helloworld

需要等待10s的动态hello world

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <script>
        // JavaScript代码开始
        console.log('开始等待10秒...');

        setTimeout(function() {
          console.log('10秒过去了!');
          document.write("Hello World");
        }, 10000);

        // JavaScript代码结束
    </script>
</body>
</html>

react helloworld

需要等待10s的动态hello world

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React Hello World</title>
    <!-- 引入React和ReactDOM库 -->
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
</head>
<body>
    <!-- React组件的容器 -->
    <div id="root"></div>

    <script>
        // 使用React.createElement创建React元素
        const element = React.createElement(
            'h1',
            null,
            'Hello World'
        );

        // 将React元素渲染到页面上
        setTimeout(function(){
          ReactDOM.render(element, document.getElementById('root'));
          console.log('10秒过去了!');
        }, 10000);
    </script>
</body>
</html>

从helloworld到helloworld!

html需要更改定义的标签内容。

<p>Hello World!</p>

js需要更改dom

document.write("Hello World!");

reactjs需要更改element

                                            
const element = React.createElement(
    'h1',
     null,
     'Hello World!'
);

vitural dom

我们从以上react的程序里看到,react创建了element然后渲染。

这里的element不是真正的dom。document.getElement获取的是真实的dom和react创建的不是一个。真正的ui界面功能很富足,如果每次所有元素都重新加载真实的dom性能很低,而有些程序仅仅变动的是界面的某些数值,完全重新加载dom就显得很笨重。

vitural dom是javascript提出的概念,而不是react特有,react很好的利用该概念。

vitural dom是在本地的内存虚拟个dom,当js/react组件或者属性发生变化时,js/react重建dom, 然后diff新旧dom的区别,将差异应用到真实的dom,实现ui的更新。

从helloworld到helloworld!,react只更新了一个element,如果真实界面上很多element,真实的dom其他的element就不会受影响,ui仅更新该element的属性,效率很高。


原文地址:https://blog.csdn.net/solinger/article/details/142460387

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!