react Context文档阅读

This commit is contained in:
2023-05-30 00:27:04 +08:00
parent 4ce0974356
commit a0ed38fd29

View File

@@ -512,6 +512,39 @@ function tasksReducer(tasks, action) {
} }
} }
``` ```
## Context
如果需要在先祖节点和子孙节点间隔多级时从先祖节点向子孙节点传递数据可以使用Context.
Context使用如下
### 创建Context
```js
import { createContext } from 'react';
export const LevelContext = createContext(1);
```
### 子孙组件从Context中获取值
```js
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
export default function Heading({ children }) {
const level = useContext(LevelContext);
// ...
}
```
### 先祖节点提供Context
```js
import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
<section className="section">
<LevelContext.Provider value={level}>
{children}
</LevelContext.Provider>
</section>
);
}
```