含义及用处:
上下文:用于跨层级传递值
基本写法:
创建上下文:const demo = React.createContext()
获取 & 提供 (管道) 上下文:demo.Provider; // 注意这里没有()
Context API
Ctx=React.createContext()
Ctx.Provider
Class.contextType
一般在Component 里声明为 static contextType=CtxCtx.Consumer
Context 的使用:
- 一个组件只能订阅一个
context
,并且是类组件,类组件使用contextType
- 函数组件不可使用contextType,需要使用到
consumer
- Consumer可以用于类组件 和 func组件
Consumer可以挂在 多个 context,但是contextType不行
多Context使用:
Page页:
Context:Context的需要一一对应,取别名
FuncComponent 页的使用: