当前位置: 首页 > news >正文

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的属性,效率很高。


http://www.mrgr.cn/news/34420.html

相关文章:

  • Android RecyclerView 实现 GridView ,并实现点击效果及方向位置的显示
  • 《机电工程技术》
  • 西门子PCS7在CFC中如何连接DB块中的变量
  • 【智能制造-32】通信冗余
  • 基于python深度学习遥感影像地物分类与目标识别、分割实践技术
  • 全流程管理的商标管理软件如何实现一站式品牌保护?
  • 【安装教程】Windows环境下Neo4j的安装与配置
  • Redis面试常见问题
  • Matplotlib-数据可视化详解
  • 【项目开发】跨学科合作平台原型设计
  • 如果在事务中使用update语句更新但是条件中没有使用主键,会使用什么级别的锁?
  • 利用代码,玩转腾讯云脱敏服务:Java、Python、PHP案例集
  • 【常见框架漏洞】ThinkPHP、struts2、Spring、Shiro
  • mysql数据库设置主从同步
  • 828华为云征文|Flexus云服务器X实例实践:部署Alist文件列表程序
  • Web端云剪辑解决方案,可实现移动端、PC、云平台无缝兼容
  • 项目总结,路径匹配的业务逻辑
  • 软件测试常见面试题
  • 部署wordpress项目
  • VBA日历进度