> For the complete documentation index, see [llms.txt](https://1425816423.gitbook.io/my-knowledge-base/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://1425816423.gitbook.io/my-knowledge-base/qian-duan-ji-shu/react/react-zu-jian-tong-xun.md).

# React组件通讯

## 目录

## 简介

React组件通讯常见的有4种类型：

* 父传子
* 子传父
* 祖先传子孙
* 兄弟组件之间通讯

常用的方式大致有：

* Props
* Event
* Context
* 状态提升
* 状态管理库

## 父传子

### Props

直接将状态传入子组件的Props中。当props改变时，子组件会重新渲染。

```tsx
// app.jsx
import { useState } from "react";
import Child from "./Child";

export default function App() {
  const [num, setNum] = useState(0);
  function addNum() {
    setNum((num) => num + 1);
  }

  return (
    <div className="App">
      <Child num={num} />
      <button onClick={addNum}>+ 1</button>
    </div>
  );
}

// child.jsx
export default function Child(props) {
  return <div>{props.num}</div>;
}
```

## 子传父

### Event

```tsx
import { useState } from "react";
import Child from "./Child";

export default function App() {
  const [num, setNum] = useState(0);
  function addNum(num) {
    setNum(num);
  }

  return (
    <div className="App">
      <Child num={num} addNum={addNum} />
    </div>
  );
}
```

## 祖先传子孙

### Context

## 兄弟组件之间

### 状态提升

react并没有提供兄弟组件之间的通讯方法，要实现兄弟组件通讯，通常是进行状态提升，即将状态提升到两个兄弟组件的父组件中。

## 状态管理库
