编写 ToDoList 列表
根据官网提示自行安装 create-react-app 项目。
编写 HelloWord 组件
react 编写组件提供两种方式,一种为 class 组件形式,也叫有状态组件;一种为 function 组件形式,也叫做无状态组件。
其中,class 组件形式如下:
1 |
|
function 组件形式如下:
1 |
|
如果返回内容为多行,可以在 return 后添加 ( ...代码 ),class 组件也是如此, 即:
1 |
|
JXS 语法
在 react 组件中使用 JXS 注释内容有两种方式;
- 一种为单行注释
1 |
|
- 一种为多行注释
1 | import React from 'react' |
编写标签,给标签添加类名需要注意使用 className,即
1 |
|
使用 label 时,注意使用 htmlFor,即:
1 |
|
解析 html 标签内容使用 dangerouslySetInnerHTML,即:
1 |
|
编写 ToDoList 组件
1 |
|
编写完成,在该项目根目录 index.js 引入该组件后在界面可查看内容。
删除 ToDoList
1 | import React, {Component} from 'react' |
添加 ToDoList 列表内容
1 |
|
父子组件传值
父组件:
1 |
|
子组件:
1 |
|
PropsTypes 校验传递的值
1 |
|
ref属性
使用 ref 获取值。
1 | import React, {Component} from 'react' |
生命周期函数
生命周期函数就是在某一时刻自动执行的函数。
初始化阶段 (
Initialization)挂载阶段(
Mounting)
componentWillMount:组件即将挂在界面前执行。
1 | componentWillMount() { |
render:页面props或state发生变化时执行。
1 | render() { |
componentDidMount:组件挂在完成时执行。
1 | componentDidMount() { |
- 请求接口可以放在该生命周期中。
- 更新阶段 (
Updation)
- shouldComponentUpdate:在组件更新前自动执行。
1 | shouldComponentUpdate() { |
要求必须返回布尔值。
- componentWillUpdate:组件更新时执行。
1 | componentWillUpdate() { |
- componentDidUpdate:组件更新后执行。
1 | componentDidUpdate() { |
- componentWillReceiveProps:在子组件中使用,子组件接收
prop该函数就会执行。
1 | componentWillReceiveProps() { |
子组件接收到父组件传递过来的参数,父组件render函数重新被执行,这个生命周期就会被执行。
也就是说这个组件第一次存在于Dom中,函数是不会被执行的;
如果已经存在于Dom中,函数才会被执行。