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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM