react-context 和contextType

import React, { Component,createContext } from 'react';

const OnLineContext=createContext()
//可以传入默认值
const BatteryContext=createContext(90)

class Middle extends Component{
  render(){
    return(
      <Leaf />
    )
  }
}

class Leaf extends Component {
  state = {  }
  render() { 
    return ( 
      <BatteryContext.Consumer>
        {
          battery=>(
            <OnLineContext.Consumer>
              {
                online=>(
                <h1>battery:{battery} online:{online?'在线':'不在线'}</h1>
                  )
              }
            </OnLineContext.Consumer>
          )
        }
      </BatteryContext.Consumer>
     );
  }
}
 
class App extends Component {
  state = { 
    battery:60,
    online:false
   }
  render() { 
    const {online}=this.state
    console.log(online)
    return ( 
      <BatteryContext.Provider value={this.state.battery}>
        <OnLineContext.Provider value={online}>
          <button onClick={()=>this.setState({battery:this.state.battery-1})}>Press</button>
          <Middle />
          <button onClick={()=>this.setState({online:!online})}>Switch</button>
        </OnLineContext.Provider>
      </BatteryContext.Provider>
     );
  }
}
 
export default App;

 contextType 可以不写comsumer

class Leaf extends Component {
  state = {  }
  static contextType=BatteryContext;
  render() { 
    const battery=this.context
    return ( 
      <h1>battery:{battery}</h1>
     );
  }
}
原文地址:https://www.cnblogs.com/lxz-blogs/p/12792980.html