# 使用hooks解决react组件间通信
提供一个简单的使用hooks解决react组件间通信的demo
# 准备
# 环境准备
node v12.13.1
npm 6.12.1
create-react-app 3.3.0
// 可根据自己情况灵活选择
1
2
3
4
5
2
3
4
5
# 搭建结构
create-react-app hooks-demo
cd hooks-demo
npm run start
1
2
3
2
3
# 删除无用文件
最终目录结构如下:

# 搭建静态结构
# 目标功能

如上图所示:
- 点击
add向列表中添加元素 - 点击
-删除对应元素 - 点击
clear清空列表
# 组件结构

可以发现,Detail组件展示列表的数据,将要被App、 Detail、 Header三个组件分别操作
主要代码如下:
const App = () => {
return (
<section className="App">
<div style={{ marginBottom: "15px" }}>
<b>hooks-demo</b>
<button>clear</button>
</div>
<Header />
<Detail />
</section>
)
}
const Detail = () => {
return (
<section className="detail">
<ul className="detail__list">
<li className="detail__list-item">
<span>张三</span>
<button className="detail__list-item-del">-</button>
</li>
<li className="detail__list-item">
<span>李四</span>
<button className="detail__list-item-del">-</button>
</li>
<li className="detail__list-item">
<span>王五</span>
<button className="detail__list-item-del">-</button>
</li>
</ul>
</section>
)
}
const Header = () => {
return (
<section className="header">
<input type="text" className="header__input" />
<button className="header__confirm">add</button>
</section>
)
}
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
39
40
41
42
43
44
45
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
39
40
41
42
43
44
45
# 搭建动态结构
新建hooks.jsx,主要代码如下:
const Types = {
ADD_ITEM: "ADD_ITEM",
DEL_ITEM: "DEL_ITEM",
CLEAR_ALL: "CLEAR_ALL"
}
export const ActionCreators = {
add: (item) => ({ type: Types.ADD_ITEM, data: item }),
del: (index) => ({ type: Types.DEL_ITEM, data: index }),
clear: () => ({ type: Types.CLEAR_ALL }),
}
export const DefaultData = { list: [] }
export const Reducer = (state, action) => {
switch (action.type) {
case Types.ADD_ITEM:
return { ...state, list: [...state.list, action.data] }
case Types.DEL_ITEM:
return { ...state, list: state.list.filter((_, index) => index !== action.data) }
case Types.CLEAR_ALL:
return { ...state, list: [] }
default:
return state
}
}
export const Context = React.createContext({})
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
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
对App.jsx、 Detail.jsx、 Header.jsx分别做如下修改:



最终效果如下:

# 参考资料
- react.js小书 (opens new window) 小书详细描述了 react 及 redux 的原理
- react-learn-ts (opens new window) 我在学习react时积累的一个demo,其中更完整地使用的react的各项api
- todolist (opens new window) 一个简易的 todolist,以上的两个demo灵感均来源于此