前端知识点简记

react context

2021-12-20  本文已影响0人  IOneStar

react context

React.createContext, Provider(数据提供者), Consumer(数据消费者), Class.contextType

  1. React.createContext 创建一组 Provider,将数据下发给自身组件树中任意层级的 Consumer。
const appContext = React.createContext(defaultValue);
const { Provider, Consumer } = appContext;
  1. Provider 对组件树进行包裹,并传入 value 属性
<Provider value={title: this.state.title}>
    <Title/>
<Provider/>
  1. Consumer,需要接受一个返回组件的函数作为子元素
<Consumer>
    {value => <div>{value.title}<div/>}
<Consumer/>
  1. Class.contextType
class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* 在组件挂载完成后,使用 MyContext 组件的值来执行一些有副作用的操作 */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* 基于 MyContext 组件的值进行渲染 */
  }
}
MyClass.contextType = MyContext;

此属性可以让你使用this.context来获取最近Context上的值。这儿有个疑问:静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。?
也可以使用 使用 static 这个类属性来初始化contextType
验证如下,

class A {
    static prop = 1;
    
    getProp() {
        console.log(this.prop);
    }
}
const a = new A();
console.log(a.prop); // undefined
a.getProp(); // undefined
class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* 基于这个值进行渲染工作 */
  }
}

useContext<MyContext>
相当于,static contextType = MyContext<MyContext.Consumer>
Class.contextType 和 Context.Consumer 的区别:
Class.contextType 使用时会自动在组件上添加一个属性context,存储离当前组件最近的Provider提供的数据,不能写多个

  1. Static contextType and class.contextType
  2. useContext
  3. context.Consumer

三种消费context的形式。

参考

React 之 Context 源码分析与实践

上一篇 下一篇

猜你喜欢

热点阅读