前言

eg:代表代码对照 若文章有误,欢迎读者留言反馈

脚手架创建React项目

全局安装React脚手架
npm install -g create-react-app
构建一个my-app的项目
create-react-app my-appnpx create-react-app my-app

清除文件[全部删除]

  • App.css
  • App.test.js
  • index.css
  • logo.svg
  • reportWebVitals.js
  • setupTests.js

清除入口文件内容
只保留下面这部分,严格模式等都清除

1
2
3
4
5
6
7
8
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<App />
)

清除根组件【顶级组件】内容
全部清除

一般写个类组件,快捷键rcc

函数组件及注意事项【快捷键 rfc

  1. jsx必须得有唯一的根标签
  2. 函数名称大写,遵循大驼峰
  3. 函数组件没有实例=>没有new=>没有this,反之类组件有
  4. 函数组件没有生命周期,没有state状态,不能做首屏,发送请求,只能做展示使用[函数组件不能放数据状态,没有生命周期,没有实例,没有this,也不能使用高阶组件的语法糖(能使用高阶组件)]
1
2
3
4
5
6
7
8
9
10
11
import React from 'react'

const App = () => {
return (
<div>
hello world
</div>
)
}

export default App

类组件及注意事项【快捷键 rcc

  1. jsx必须得有唯一的根标签
  2. 类组件名称大写,遵循大驼峰
  3. 类组件有实例=>有new=>有this,反之函数组件没有
  4. 类组件有生命周期,有状态,既能做首屏,发送请求,也能做展示使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 类组件[重写了Component]
import React, { Component } from 'react'

class App extends Component {
render() {
return (
<div>
hello world
</div>
)
}
}

export default App

eg1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 函数组件
import React from 'react'

// 函数组件方法调用不需要this,注意var声明
var handleClick = () => {
console.log('hello')
}
const App1 = () => {
return (
<div>
hello world
<button onClick={handleClick}>点击</button>
</div>
)
}

export default App1

// 类组件[重写了Component]
import React, { Component } from 'react'

// 类组件方法调用需要this,注意不需要var声明
handleClick = () => {
console.log('hello')
}
class App2 extends Component {
render() {
return (
<div>
hello world
<button onClick={this.handleClick}>点击</button>
</div>
)
}
}

export default App2

React组件及分类

与Vue不同,React组件不需要注册,直接使用

React组件:以js或者jsx为后缀的文件都可以是组件
安装了如下jsx代码提示插件,文件以.jsx后缀有代码提示
vscode-React提示插件

组件的划分:容器组件和展示组件。
类组件既可以是容器组件,也可以是展示组件,函数组件只能是展示组件。

函数组件 顶级组件

  • 函数组件,本质就是一个函数,函数中有return,return后面跟jsx语法。jsx语法必须有唯一的跟标签。
  • 函数名称大写,组件名称都大写。
  • 类组件是react中常用的组件类型,是已class类继承react中Component组件来创建的。render函数必须有,
  • return后面跟jsx语法。

组件分为函数组件和类组件【后面很多地方一些功能都将会被划分为不同写法==>类组件写法、函数组件写法和两者通用写法】

小知识点:React与vue在启动上有点不同,React使用npm start启动省去了run,但是其它命令还是要带上run