react context

205 阅读1分钟

1.创建方式

  • getChildContext 方式
  • React.createContext 方式

方式1 实现

  • 父组件声明getChildContext方法并声明需要传递给子组件的类型。

  • 父组件声明childContextTypes 子组件声明contextTypes 并使用this.context.XXX形式调用

方式2 实现

  • React.createContext方式返回的是两个组件。Provider, Consumer

  • 其中 ,Provider组件声明需要传递的context属性, Consumer组件中直接使用,使用时是一个方法,参数即为context值。