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简单的多。

 

转载于:https://www.cnblogs.com/littleSpill/p/11221817.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值