React | 组件通讯-实践

组件通讯的方式

父传子

  • Props
  • Instance Mthods

子传父

  • Callback Functions
  • Event Bubbling(冒泡)

兄弟组件

  • Parent Component

跨级组件

  • Context
  • Portals
  • Global Variables
  • Observer Pattern
  • Redux等

通讯实践

父传子&&子传父

场景说明

组件说明:Parent为父组件 Child为子组件

子组件(Child)包含一个Button,用于模拟小孩收到糖果数量(count),但是最终到手的糖果数量(givenCount)是由父组件(Parent)控制的

父组件(Parent)根据子组件收到的糖果数量(count)随机选取一个随机糖果数量(givenCount)(givenCount介于0-count之间)传递给子组件(Child)

方式1:props && Callback Functions

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
// Parent.jsx
import React, {useState} from 'react';
import Child from './child';

export default function Parent() {
const [candies, setCandies ] = useState(0);
function getCandies(count) {
setCandies(count);
}

// 随机给糖果数量
const givenCount = Math.floor(Math.random() * (candies + 1));
return (
<div>
<Child candies={givenCount} getCandiesFn={getCandies}></Child>
</div>
)
}


// Child.jsx
import React, { useState } from 'react';

export default function Child(props) {
const [count, setCount ] = useState(0);
const givenCount = props.candies;
function changeCount() {
setCount(count+1);
props.getCandiesFn(count);
}
return (
<div>
<h3>I am have {count} candies! yeah!</h3>
{/* giveCount是由父组件决定的 */}
<h3>But my mother only give me {givenCount} candies actually!</h3>
<button onClick={changeCount}>Click</button>
</div>
)
}
实现效果

方式2: refs && Event Bubbling

原理说明
  • refs原理:父组件可以通过refs来直接调用子组件实例
  • event bubbling:此方法跟react本身没有关系,利用的是原生dom元素的事件冒泡机制
1
2
3
4
// Parent.jsx


// Child.jsx

实现效果

兄弟组件

兄弟组件之间通信把父组件作为中间桥梁进行传值,实现步骤同上,不再赘述

跨级组件

参考

30分钟精通十种React组件之间通信的方法