React介绍
官网的介绍:用于构建用户界面的 JavaScript 库
核心的特性有三个
- 声明式:命令式编程、声明式编程
- 组件化:函数式组件、类组件
- 一次学习,随处编写:react只负责编写UI,在不同的终端上使用不同的界面渲染器来显示界面。
详情见B站UP主objtube的卢克儿的这期教程,React定义与三大特性
JSX是Babel定义的一种语法格式,遵循JSX编写的组件可以通过Babel编译成原生的Js代码。
比如:
// 使用JSX
class HelloMessage extends React.Component {
render() {
return (
<div>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="Taylor" />,
document.getElementById('hello-example')
);
// 未使用JSX
class HelloMessage extends React.Component {
render() {
return React.createElement(
"div",
null,
"Hello ",
this.props.name
);
}
}
ReactDOM.render(React.createElement(HelloMessage, { name: "Taylor" }), document.getElementById('hello-example'));
Tips:
Babel官网:Babel是一个js代码编译器。
可以在Babel提供的在线工具中练习jsx语法并查看编译好的原生js代码。
React环境准备
方式一:在浏览器中编写代码
方式二:搭建本地开发环境
本地环境
- node.js:node.js官网
- Create React APP:Create React APP
Create React APP
一个不需要构建配置就可以创建React应用的工具。可以跨平台运行。cra官网
主要功能:
- 创建react应用
- 用户手册
npx create-react-app my-app # 创建my-app项目
cd my-app # 进入my-app项目
npm start # 启动 my-app项目
生成文件的目录结构如下:
my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
└── setupTests.js
cra的核心理念:唯一依赖、零配置、无锁定
-
One Dependency: There is only one build dependency. It uses webpack, Babel, ESLint, and other amazing projects, but provides a cohesive curated experience on top of them.
-
No Configuration Required: You don’t need to configure anything. A reasonably good configuration of both development and production builds is handled for you so you can focus on writing code.
-
No Lock-In: You can “eject” to a custom setup at any time. Run a single command, and all the configuration and build dependencies will be moved directly into your project, so you can pick up right where you left off.