react Context文档阅读
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user