react入门笔记
记录学习react的入门笔记。
脚手架
我是从create react app
入门的,但是最近发现umi
和vue-cli
配置比较像;
1
2
3
npm create @umijs/umi-app
npm i
npm start
工程结构如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
│ .editorconfig
│ .gitignore
│ .prettierignore
│ .prettierrc
│ .umirc.ts
│ package.json
│ README.md
│ tsconfig.json
│ typings.d.ts
│
├─mock
│ .gitkeep
│
└─src
└─pages
index.less
index.tsx
我们一般就在scr -> pages
目录下新建各类模块文件夹,写页面组件。
组件分类
react分为class组件和函数组件,关于两者的区别可以写好多,但入门还是先看看语法上的区别就好,写多了慢慢体会。
JSX语法
JSX语法就是在JS里写HTML,绑定变量采用{value}
语法,样式类名需要使用className
,除了HTML内置组件外,自定义组件需要首字母大写<Components/>
;例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Div extends React.Component {
render() {
return (
<div></div>
)
}
}
function DIV() {
return (
<div className='div'></div>
)
}
组件数据
组件数据分为内部和外部,react把组件内用到的可变数据叫做state
,从外部接收的数据称为props
;
写习惯了Vue2的同学,习惯性的把用到的组件内部数据都定义在data
中,因为data
中的数据都是响应式的,在react中,state
中的数据才是动态的,如果单纯是个类上的属性(针对class组件)或者是个普通变量(针对函数组件),那它就不是动态的,看个例子:
1
2
3
4
5
6
7
8
9
const Div = () => {
let title = 'index'
const onclick = () => {
title = 'index2'
}
return (
<h1 onClick={onclick}>{title}</h1>
)
}
点击标题并不会将h1的标题替换,因为title
不是state
,不是组件的状态,所以改变title
并不会引起UI
的重新渲染;
1
2
3
4
5
6
7
8
9
10
11
const Div = () => {
const [title,setTitle] = useState({title:'index'})
const onclick = () => {
setTitle(t => {
return {title1:'index2'}
})
}
return (
<h1 onClick={onclick}>{title.title}</h1>
)
}
把title
转成state就行了。修改state会引起UI重绘。
这个例子有个问题:class
组件中,使用setState
会合并state
成为一个大对象;在函数式组件内,会直接替换原来的state
如果运行上面那个例子,点击title会直接报错,因为找不到title.title