React的contextType的使用方法简介

上一篇介绍了Context的使用方法。可是Context会让组件变得不纯粹,由于依赖了全局变量。因此这决定了Context通常不会大规模的使用。因此通常在一个组件中使用一个Context就好。html

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

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

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;

 

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

咱们只须要修<Leaf/>组件的代码就能够。函数

 

首先咱们用static来声明contextType:this

static contextType = BatteryContext;

 

 

这样在运行时就能够获取到一个新的属性。咱们来接收他。
const battery = this.context;

 

这样Consumer就能够彻底再也不使用了。
 return<h1>Battery : {battery}</h1>

 

 所有代码:spa

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;

 

 

效果图:3d

 

效果和使用Consumer没有什么区别。可见只有一个Context的时候,使用contextType要比使用Consumer简单的多。
相关文章
相关标签/搜索