认识
- 介绍
- 构建用户界面的 JavaScript 库
- 不是框架
- React 主观意愿
- React 仅仅负责 View 层渲染
- 是一个视图渲染的工具库,不做框架的事情
- 总结
- 只负责视图渲染,不要要求 React 干其他的事情
简单使用
- 添加根容器
<div id="app">...</div>
- 引入 CDN 脚本
- 创建 React 组件
- React: 提供 React API(处理视图的 API 集合)
- React-DOM:从 render → 虚拟 DOM → 真实 DOM
- 继承
React.Component
render
函数返回一个视图
CDN Links - 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>Learning React</title>
</head>
<body>
<div id="app"></div>
<!-- 开发环境 -->
<script
crossorigin
src="<https://unpkg.com/react@17/umd/react.development.js>"
></script>
<script
crossorigin
src="<https://unpkg.com/react-dom@17/umd/react-dom.development.js>"
></script>
<!-- 生产环境 -->
<!-- <script
crossorigin
src="<https://unpkg.com/react@17/umd/react.production.min.js>"
></script>
<script
crossorigin
src="<https://unpkg.com/react-dom@17/umd/react-dom.production.min.js>"
></script> -->
<script src="./js/01简单使用.js"></script>
</body>
</html>
const span = React.createElement(
"span",
{
className: "text",
key: 1,
},
"This is a span"
);
ReactDOM.render(
React.createElement(
"div",
{
className: "container",
},
[span]
),
document.getElementById("app")
);
使用 class 创建组件
class MyButton extends React.Component {
constructor(props) {
super(props);
this.state = {
openStatus: false,
};
}
render() {
const oP = React.createElement(
"p",
{
className: "text",
key: 1,
},
this.state.openStatus ? "打开状态" : "关闭状态"
);
const oBtn = React.createElement(
"button",
{
key: 2,
onClick: () =>
this.setState({
openStatus: !this.state.openStatus,
}),
},
this.state.openStatus ? "关闭" : "打开"
);
const oWrapper = React.createElement(
"div",
{
className: "container",
},
[oP, oBtn]
);
return oWrapper;
}
}
const span = React.createElement(
"span",
{
className: "text",
key: 1,
},
"This is a span"
);
ReactDOM.render(React.createElement(MyButton), document.getElementById("app"));
Create a New React App
- npx: npm5.2+ 的包运行工具
- create-react-app 内部的工程化依赖:
babel/webpack
npx create-react-app my-react-app
cd my-react-app
npm start
函数组件写法