zoukankan      html  css  js  c++  java
  • React的contextType的使用方法简介

    上一篇介绍了Context的使用方法。但是Context会让组件变得不纯粹,因为依赖了全局变量。所以这决定了Context一般不会大规模的使用。所以一般在一个组件中使用一个Context就好。

    由于Consumer的特性,里面的代码必须是这个函数的返回值。这样就显得复杂与不优雅了。那该怎么解决呢?这样contextType就派上用场了。
     

    还拿上一篇的demo来举例。并且修改它。 上一篇的代码:

    import React, { Component, createContext } from 'react';
    
    const BatteryContext = createContext();
    
    //声明一个孙组件
    class Leaf extends Component {
      render() {
        return (
          <BatteryContext.Consumer>
            {
              battery => <h1>Battery : {battery}</h1>
            }
          </BatteryContext.Consumer>
        )
      }
    }
    
    //声明一个子组件
    class Middle extends Component {
      render() {
        return <Leaf /> 
      }
    }
    
    class App extends Component {
      render(){
        return (
          <BatteryContext.Provider value={60}>
            <Middle />
          </BatteryContext.Provider>
        );
      }
    }
    
    export default App;

     接下里我们修改他,使他更加优雅一些:

    我们只需要修<Leaf/>组件的代码就可以。

    首先我们用static来声明contextType:

    static contextType = BatteryContext;
    这样在运行时就可以获取到一个新的属性。我们来接收他。
    const battery = this.context;
    这样Consumer就可以完全不再使用了。
     return<h1>Battery : {battery}</h1>

     全部代码:

    import React, { Component, createContext } from 'react';
    
    const BatteryContext = createContext();
    
    //声明一个孙组件
    class Leaf extends Component {
      static contextType = BatteryContext;
      render() {
        const battery = this.context;
        return<h1>Battery : {battery}</h1>
      }
    }
    
    //声明一个子组件
    class Middle extends Component {
      render() {
        return <Leaf />
      }
    }
    
    class App extends Component {
      state = {
        battery: 60,
      }
      render() {
        const { battery } = this.state;
        return (
          <BatteryContext.Provider value={battery}>
            <button
              type="button"
              onClick={() => this.setState({ battery: battery - 1 })}
            >
              减减
            </button>
            <Middle />
          </BatteryContext.Provider>
        );
      }
    
    }
    
    export default App;

    效果图:

    效果和使用Consumer没有什么区别。可见只有一个Context的时候,使用contextType要比使用Consumer简单的多。
  • 相关阅读:
    静态检查lua语法工具luacheck
    centos7系列:
    git submodule 教程
    CENTOS 7 安装redis
    python基本语法:
    彻底理解lib和dll
    C++语言的设计与演化(空白):
    《Effective C++》 目录:
    C++进阶书籍(转)
    学习的心态(转)
  • 原文地址:https://www.cnblogs.com/littleSpill/p/11221817.html
Copyright © 2011-2022 走看看