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