1.函数式组件适用于简单组件的开发定义
函数类型不能作为React的节点的,例如下述代码
<!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>Document</title> <link rel="shortcut icon" href="favicon.ico" /> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script type="text/babel"> function demo(){ return <h1>前端工程师</h1> } ReactDOM.render(demo,document.getElementById("test")); </script> </body> </html>
其会报错
2.引入图标
<link rel="shortcut icon" href="favicon.ico" />
3.将1中的函数进行组件引用的时候
要将组件名改为大写的组件名
记住引入组件的时候,一定要让标签闭合,或者
<!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>Document</title> <link rel="shortcut icon" href="favicon.ico" /> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script type="text/babel"> function Demo(){ return <h1>前端工程师</h1> }; ReactDOM.render( <Demo/>,document.getElementById("test")); </script> </body> </html>
4.在采用babel时创建函数式组件的时候,在函数式组件当中加入console.log(this) //在这里的this是undefined,因为babel执行时采用了严格模式
<!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>Document</title> <link rel="shortcut icon" href="favicon.ico" /> </head> <body> <div id="test"></div> <script src="./react-resource/react.development.js"></script> <script src="./react-resource/react-dom.development.js"></script> <script src="./react-resource/babel.min.js"></script> <script type="text/babel"> function MyComponent(){ return <h1>前端工程师</h1> console.log(this) //在这里的this是undefined,因为babel执行时采用了严格模式 }; ReactDOM.render( <MyComponent/>,document.getElementById("test")); </script> </body> </html>
5.测试babel采用了严格模式,将代码复制粘贴到babel官方网站当中,查看是否是"use strict"
6.渲染组件到页面上的过程A.React解析组件标签,找到MyComponent组件B.发现组件是由函数式组件定义的,随后调用该函数,将返回的虚拟DOM转为真实DOM