1.使用jsx创建DOM元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello-react</title> </head> <body> <!-- 在这里创建一个容器 --> <div id="test"></div> <!-- 先在这里引入react核心库,注意要先引入核心库,再去引入其他库 --> <script src="./react-resource/react.development.js"></script> <!-- 引入react-dom,便于对DOM进行操作 --> <script src="./react-resource/react-dom.development.js"></script> <!-- 引入babel.min.js,便于将jsx转化为js --> <script src="./react-resource/babel.min.js"></script> <!-- 在这里必须要引入babel.min.js文件 --> <script type="text/babel"> const VDOM= <h1 title="test">我爱娟宝</h1>; ReactDOM.render(VDOM,document.getElementById("test")); // 如果在这里同时出现两个DOM操作,那么再在这里就会出现替换效果,就是后面那一个会替换掉前面那一个 </script> </body> </html>
2.使用js创建DOM元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>使用js创建DOM</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script type="text/javascript"> const VDOM = React.createElement('h1', { id: test, title: test }, "娟宝爱你"); ReactDOM.render(VDOM, document.getElementById("test")); </script> </body> </html>
3.用两个createElement
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>使用js创建DOM</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script type="text/javascript"> const VDOM = React.createElement('h1', { id: test, title: test }, React.createElement('span', { title: test }, "娟宝")); ReactDOM.render(VDOM, document.getElementById("test")); </script> </body> </html>
上面的这个代码是由下面的代码翻译而来的,就是在引用babel的时候,由jsx转化为js代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>使用js创建DOM</title> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script type="text/javascript"> const VDOM = (<h1 title="test"> <span>Hello!react</span> </h1>); ReactDOM.render(VDOM, document.getElementById("test")); </script> </body> </html>