1. 原始react 程序初体验
(1) npm init -y 生成一个package.json文件
(2)npm install react react-dom
(3)程序设计:reactElement 为一个react元素。root为根元素(<div id="app></div>)
React 负责创建元素(html部分),ReactDOM负责把创建内容,加入到页面中指定部分。
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const reactElement = React.createElement("h1", { className: "title" }, "hello john!!!")
const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(reactElement);
</script>
</body>
(4)运行效果
2.创建react元素两种方法:
(1) 上述1中:
React.createElement("h1", { className: "title" }, "hello john!!!")
(2) jsx语法。
const reactElement = <h1 class="title">hello john!!!</h1>
jsx语法,看起来像Html,其实并不是html , 这部分代码是写在js中的。但是,当替换React.createElement之后,发现程序并不能运行。因为,浏览器不能解析jsx语法,于是乎,就引入我们的脚手架工具。create-react-app (简称:cra)。靠babel去解析。
<body>
<div id="app">
</div>
<script>
//const reactElement = React.createElement("h1", { className: "title" }, "hello john!!!")
const reactElement = <h1 class="title">hello john!!!</h1>
const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(reactElement);
</script>
</body>
3.脚手架工具:create-react-app
create-react-app是一个快速创建React开发环境的工具,底层由Webpack构建,封装了配置细节,具体使用如下:
npx create-react-app react-basic
1. npx 是安装Nodejs之后,自带的一个工具,无需专门安装(如同 npm)
2. create-react-app 核心包(固定写法),用于创建React项目
3. react-basic React项目的名称(可以自定义)
上述jsx语法,放入脚手架工具生成的react-demo中。
4. 组件:分为函数组件,和类组件:
(1) 产生原因:
- 我们不能把所有的react元素(也就是reactElement)程序都写在index.js 页面中,要进行适当的分割。
- 组件类似函数一样,可以复用。
(2) 函数组件,16.0版本以前称为无状态组件。之后,加入了hook.功能非常强大,不能在称呼人家为无状态组件了。现在基本可以取代类组件了。
如图13行代码处写了一个<App/>,当然也可以写成两个。
root.render(
<div>
{/* {reactEle} */}
<App/>
<App/>
</div>
);
最终页面现实效果是:
(3)类组件,将上述(2)函数组件,修改为类组件。效果是一样的。