React基础知识

react基础知识

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from 'react';

//定义一个 MyApp 组件
class MyApp extends React.Component{
render(){
const boss = '校长'
return (
<div>
<h2>学校,{boss}</h2>
<MyApp2></MyApp2>
</div>
)
}
}

//定义 MyApp2 组件给MyApp使用
class MyApp2 extends React.Component{
render(){
const boss = '主任'
return <h3>办公室,{boss}</h3>
}
}

export default MyApp;

组件之间传递数据

  • props传递数据:使用<组件 数据=“值”>的形式传递
  • 组件内部使用 this.props获取值
  • 如果组件只有render函数,还可以用函数的形式写组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//定义一个 MyApp 组件
class MyApp extends React.Component{
render(){
const boss = '校长'
return (
<div>
<h2>学校,{boss}</h2>
<MyApp2 boss="主任"></MyApp2>
</div>
)
}
}

//定义 MyApp2 组件给MyApp使用
class MyApp2 extends React.Component{
render(){
// const boss = '主任'
return <h3>办公室,{this.props.boss}</h3>
}
}

export default MyApp;

组件内部state

  • 组件内部通过state管理状态
  • JSX本质是js,所以直接用数组.map渲染列表
  • Constructor设置初始状态,记得执行super(props)
  • state就是一个不可变的对象,使用this.state获取
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
38
import React from 'react';

//定义一个 MyApp 组件
class MyApp extends React.Component{
render(){
const boss = '校长'
return (
<div>
<h2>学校,{boss}</h2>
<MyApp2 boss="主任"></MyApp2>
</div>
)
}
}

//定义 MyApp2 组件给MyApp使用
class MyApp2 extends React.Component{
constructor(props){
super(props)
this.state = {
staff:['甲','乙','丙','丁']
}
}
render(){
return (
<div>
<h3>办公室,{this.props.boss}</h3>
<ul>
{this.state.staff.map(v=>{
return <li key={v}>{v}</li>
})}
</ul>
</div>
)
}
}

export default MyApp;

事件

  • onClick点击事件

JSX里使用onClick={()=>this.函数名()}来绑定事件

  • this引用的问题,需要在构造函数里用bind绑定this
  • this.setState修改state,记得返回新的state,而不是修改
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
//定义 MyApp2 组件给MyApp使用
class MyApp2 extends React.Component{
constructor(props){
super(props)
this.state = {
staff:['甲','乙','丙','丁']
}
}
addStaff(){
this.setState({
staff:[...this.state.staff,"新员工"+Math.random()]
})
}
render(){
return (
<div>
<h3>办公室,{this.props.boss}</h3>
<button onClick={()=>this.addStaff()}>新员工加入</button>
<ul>
{this.state.staff.map(v=>{
return <li key={v}>{v}</li>
})}
</ul>
</div>
)
}
}

export default MyApp;

生命周期

react组件内部有若干钩子函数,在组件不同的状态执行

  • 初始化周期(页面组件第一次渲染所要执行的所有函数)
  • 组件重新渲染(更新)生命周期(props、state变化导致页面状态发生变化时执行的函数)
  • 组件卸载生命周期(比如某个组件离开这个页面)
------ 本文结束 ------
0%