From a0ed38fd291d2d2af8916a01c2410680d2209b39 Mon Sep 17 00:00:00 2001 From: rikako <496063163@qq.com> Date: Tue, 30 May 2023 00:27:04 +0800 Subject: [PATCH] =?UTF-8?q?react=20Context=E6=96=87=E6=A1=A3=E9=98=85?= =?UTF-8?q?=E8=AF=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- react/react文档.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) 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} + +
+ ); +} +```