上一篇介紹了Context的使用方法。可是Context會讓組件變得不純粹,由於依賴了全局變量。因此這決定了Context通常不會大規模的使用。因此通常在一個組件中使用一個Context就好。html
還拿上一篇的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;
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