React-contextType

522 阅读1分钟
/**Context 提供了一种方式,能够让数据在组件树中传递时不必一级一级的手动传递
 * contextType(静态属性) 可以简化 context 的使用,不使用 consumer 也可以共享变量
 * 使用contextType必须是在类组件中,并且只能用一个Provider
 */

import { Component,createContext } from 'react'
//import { View, Text,Button } from '@tarojs/components'

const BatteryContext = createContext();//如果有参数,则参数为默认值
const OnlineContext = createContext(true);

class Leaf extends Component{
    //申明静态变量,contextType将context直接赋值于contextType
    static contextType = BatteryContext;

    render(){
        //在render中,可以直接访问this.context获取共享变量,这样就可以不使用Consumer
        const battery = this.context;
        return (
        <h1>Battery:{battery}</h1>
        )
    }
}
class Middle extends Component{
    render(){
        return <Leaf/>
    }
}

export default class Index extends Component {
      state = {
        battery:100,
      }
  render () {
    const {battery,online} = this.state;
    return (
        <BatteryContext.Provider value={battery}>
        <Middle/>
        <Button onClick={()=>this.setState({battery:battery-1})}>
            Button
        </Button>
        </BatteryContext.Provider>
    )
  }
}