1.使用js创建虚拟DOM(不推荐使用)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js创建虚拟DOM</title> <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> <!-- 准备一个容器 --> <div id="test"></div> </body> <script type="text/javascript"> // 使用js创建虚拟DOM const vDom = React.createElement('h1',{title:'hello'},React.createElement('span', {}, 'Hello,React')) //react渲染 ReactDOM.render(vDom, document.getElementById("test")) </script> </html>
2.使用jsx创建虚拟DOM
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jsx创建虚拟DOM</title> <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> <!-- Don't use this in production: --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <!-- 准备一个容器 --> <div id="test"></div> </body> <script type="text/babel"> // 使用jsx创建虚拟DOM // babel会帮我们将jsx转化为js形式的DOM创建,本质上没有变化,实际上就是jsx简化了我们的编写 const vDom = ( <h1> <span>Hello,React</span> </h1> ) //react渲染 ReactDOM.render(vDom, document.getElementById("test")) </script> </html>
3.虚拟DOM与真实DOM
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jsx创建虚拟DOM</title> <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> <!-- Don't use this in production: --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <!-- 准备一个容器 --> <div id="test"></div> <!-- 真实DOM --> <h1 id="trueDom"> <span>Hello,React</span> </h1> </body> <script type="text/babel"> // 使用jsx创建虚拟DOM const vDom = ( <h1> <span>Hello,React</span> </h1> ) //react渲染 ReactDOM.render(vDom, document.getElementById("test")) // 拿到真实DOM const tDom = document.getElementById("trueDom") debugger; console.log("虚拟DOM",vDom) console.log("真实DOM",tDom) // 关于虚拟DOM // 1.虚拟DOM本质上是一个Object对象 // 2.虚拟DOM相较于真实DOM拥有的属性较少,是React内部使用的 // 3.虚拟DOM会被React转化为真实的DOM展示在页面上 </script> </html>
标签:DOM,创建,React,虚拟,jsx,vDom From: https://www.cnblogs.com/jmsstudy/p/17591356.html