关于react Context的理解

关于react Context的理解

react中Contex设计的目的是为了创建在组件树中能够共享的数据,子组件获取父组件数据无需通过props的层层传递

// react创建Context,通过createContext方法创建context对象,方法中参数为context对象的默认值
context MyContext = React.createContext(defauleValue)

// 下方为顶层组件App,在顶层组件使用Provider将数据放出

function App() {
  // 需要全局共享的数据
  const color = 'blue'
  return (
  	// 使用创建的context对象的Provider元素,并将需要传递的数据放入value属性中
  	// 当Provider中的value属性值发生变化时,它内部所有的消费组件都会重新渲染
    <MyContext.Provider value={color}>
      <Son />
    </MyContext.Provider>
  )
}

中间子组件

class Son extends React.Component{
  render() { 
    return (
      <GrandSon />
    )
  }
}

孙组件,想要接收顶层组件放出的数据有两种方式
方式一:使用Consumer接收

class GrandSon extends React.Component{
  render() { 
    return (
      <MyContext .Consumer>
        {(color) => (
          <div>
            <button>{color}</button>
          </div>
        )}
      </MyContext .Consumer>
    )
  }
}

方式二:使用contextType属性接收

class GrandSon extends React.Component{
  // 指定contextType读取MyContext,React会顺着组件树往上找到最近的Provider,然后使用它的值
  static contextType = MyContext 
  render() { 
    return (
        <button>{this.context}</button>
    )
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值