# 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并没有提供兄弟组件之间的通讯方法，要实现兄弟组件通讯，通常是进行状态提升，即将状态提升到两个兄弟组件的父组件中。

## 状态管理库


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://1425816423.gitbook.io/my-knowledge-base/qian-duan-ji-shu/react/react-zu-jian-tong-xun.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
