饮水思源:https://www.bilibili.com/video/BV1wy4y1D7JT?p=9
函数式组件
函数名首字母必须大写
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Add React in One Minute</title> </head> <body> <div id="test"></div> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <!-- Load Babel --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> let 容器 = document.querySelector("#test"); function MyHeader() { return <h2>我是函数定义的组件(适用于简单组件的定义)</h2> } ReactDOM.render(<MyHeader />, 容器); </script> </body> </html>
类式组件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Add React in One Minute</title> </head> <body> <div id="test"></div> <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <!-- Load Babel --> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> let 容器 = document.querySelector("#test"); class 最简可用组件 extends React.Component { // render是放在哪里的?——“最简可用组件”的原型对象上,供实例使用。 // render中的this是谁?——“最简可用组件”的实例对象,也可以说““最简可用组件””组件实例对象 render() { console.log(this) return <h2>我是类定义的组件(适用于复杂组件的定义)</h2> } } ReactDOM.render(<最简可用组件 />, 容器); </script> </body> </html>