03-react的context

为什么要采用context

公共信息(语言、主题)如何传递给每个组件?
用props太繁琐
用redux小题大做

context是react的一种组件之间的通讯方式,它不同于props。props需要逐层传递,当组件层数过多时,显得非常的麻烦。
Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。

API

React.createContext:创建一个上下文的容器(组件), defaultValue可以设置共享的默认数据

创建文件AllContext.js 导出

export default React.createContext('zhangsan');

Provider(生产者): 和他的名字一样。用于生产共享数据的地方。value:放置共享的数据。
App.jsx

import Context from './AllContext';
this.state = { 
     name: '张三'
     }
<Context.Provider value={this.state.name}>
        <span onClick={()=>this.setState({name:'li'})}>parent </span>
      <hr/>
      <Son></Son>
</Context.Provider>

Son不做任何操作,因为context不需要逐层进行传递

class Son extends React.Component {
  constructor(props) {
    super(props);
    this.state = {}
  }
  render() {
    return (<div>
      son
      <hr />
      <Grandson></Grandson>
    </div>);
  }
}

挂载在 class 上的 contextType 属性会被重赋值为一个由 React.createContext() 创建的 Context 对象。此属性能让你使用 this.context 来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它,包括 render 函数中。
Son.jsx
Grandson.jsx

import React, { Component } from 'react';
import Context from './AllContext';
class Grandson extends Component {
  static contextType  = Context;
  render() {
    return (<div>
      Grandson {this.context}
    </div>);
  }
}

export default Grandson;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值