contextType取代了context中的Consumer。
import React, { Component, createContext } from 'react';
const Context = createContext();
const {Provider} = Context;
//声明一个子组件
class Child extends Component {
render() {
return <GrandChild />
}}
//声明一个孙组件
class GrandChild extends Component {
static contextType = Context;
render() {
const value = this.context;
return<h1>CurrentValue : {value}</h1>
}
}
class App extends Component {
state = {
currentValue: 60,
}
render() {
const { currentValue } = this.state;
return (
<Provider value={currentValue}>
<button type="button" onClick={() => this.setState({ currentValue: currentValue - 1 })} > 减1</button>
<Child />
</Provider>
);
}
}
export default App;
效果为: