diff --git a/react/react文档.md b/react/react文档.md index ca0eb21..9ebf0fc 100644 --- a/react/react文档.md +++ b/react/react文档.md @@ -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 ( +
+ + {children} + +
+ ); +} +```