07-非父子组件通信context

24 阅读1分钟

context应用场景

单纯父子组件通信,通过props就可以,但是父给后N代组件传递呢,如果都用props,代码会非常冗余,此时context就是好的解决方案。

补充:非要一个个传递,使用{...props},看着代码量少一点

context使用方式

类组件

四步骤:

  1. 通过React.createContext创建context对象
  2. 通过Context.Provider包裹需要共享元素的组件,并将共享数据通过value属性传递
  3. 子类组件引入context对象,声明HomeInfo.contextType = ThemeContext
  4. 子类组件内部使用数据this.context

step1: createContext创建context对象

image.png step2: Context.Provider提供value

image.png step3: 类组件声明contextType

image.png image.png step4: 类组件使用this.context

image.png

函数组件

四步骤:

  1. 通过React.createContext创建context对象
  2. 通过Context.Provider包裹需要共享元素的组件,并将共享数据通过value属性传递
  3. 函数组件,通过AgentContext.Consumer包裹一个带参的回调函数,回调函数中通过value展示内容

step3:函数组件,通过AgentContext.Consumer包裹一个带参的回调函数,回调函数中通过value展示内容 image.png

需要多个context对象的数据怎么弄

这里说的是,两个context对象,被一个类组件使用的情况

  1. 外层,嵌套context.provider
  2. 类组件,外层的context通过contextType+this.context方式使用;内层context通过类似函数组件的使用方式Context.Consumer+value回调函数

image.png

总结

简单数据共享可以使用context,复杂的使用redux