美文网首页React
Hook环境下的useContext与class环境下的Cont

Hook环境下的useContext与class环境下的Cont

作者: Lia代码猪崽 | 来源:发表于2020-08-30 15:40 被阅读0次

    一、回顾class的context

    1.context的作用

    Context提供了一种方式,能够让数据跨越组件层级来传递,不再需要一层一层的传递。

    2. 用法

    有接收传递过来的值有两种用法,一种是Consumer用法,还有另外一种是使用contextType

    2.1 consumer用法

    1. 使用createContext()来创建一个Provider
    2. 使用这个Provider来包裹组件,其中value属性来指定要传递的值。
    3. 在内部声明一个Consumer,通过回调函数来拿到上级传递过来的value的值。

    大概流程代码:

    <Provider value={data}>
      <Consumer>
        { data => <span>{ data }</span> }
      </Consumer>
    </Provider>
    

    2.2 contextType用法

    可以使用contextType来简化其中一个Context的获取。

    1. 使用createContext()来创建一个Provider
    2. 使用这个Provider来包裹组件,其中value属性来指定要传递的值。
    3. 通过类静态变量static contextType获取到Context
      4.this.context就能获取到传递过的值

    大致流程代码:

    <Provider value={data}>
      contextType
    </Provider>
    

    二、在Hooks环境下的Context

    依旧是可以使用Consumer的,这是JSX的实现。
    contextTypeclass类静态属性,所以不能使用。

    useContext 不但解决了Consumer难用的问题,还解决了contextType只能声明一个Context的问题,一举两得~

    import React, { useState, createContext, useContext } from 'react';
    
    const TestContext = createContext(0);
    
    function App() {
      const [count, setCount] = useState(0);
      return (
          <TestContext.Provider value={count}>
              <button onClick={() => setCount(count + 1)}>点我加一</button>
              <Test></Test>
          </TestContext.Provider>
      )
    }
    
    function Test() {
        const count = useContext(TestContext)
        return (
            <h1>{ count }</h1>
        )
    }
    
    export default App;
    

    三、总结区别

    Context 区别 Class Hook
    Consumer 可以使用 可以使用
    contextType 可以使用 不可以,因为这是类静态属性,依赖class
    useContext 不可以 推荐使用,即解决了Consumer使用不方便的问题,又解决了contextType只能有一个context的问题

    相关文章

      网友评论

        本文标题:Hook环境下的useContext与class环境下的Cont

        本文链接:https://www.haomeiwen.com/subject/djlesktx.html