react 上下文(Context)

注意: 从 React v15.5 开始 ,React.PropTypes 助手函数已被弃用,我们建议使用 prop-types 库 来定义contextTypes。
2.1首先你需要通过在终端npm install prop-types安装一个叫prop-types的第三方包

getChildContext 定义在父组件中,指定子组件可以使用的信息
childContextTypes 定义在父组件中,getChildContext 指定的传递给子组件的属性需要先通过 childContextTypes 来指定,不然会产生错误

子组件需要通过 contextTypes 指定需要访问的元素。 contextTypes 没有定义, context 将是一个空对象。

父组件定义

class Greeter extends Component{
    constructor(props){
        super(props)
        this.state={
            add:87,
            remove:88
        }
    }
    static childContextTypes = {
        add:T.number,
        remove:T.number
    }
    getChildContext() {
       const { add,remove} = this.state;
       return {
           add,
           remove
       }
    }
    render(){
        return(
            <div>
                <ComponetReflux/>
            </div>
        )
    }
}
子组件定义
class ComponetReflux extends Component{
    constructor(props){
        super(props)
        this.state={
            
        }
    }
    static contextTypes = {
        add:T.number,
        remove:T.number
    }
    render(){
        console.log(this.context)              //打印{add:87,remove:88}
        const {name,age} = this.state
        return (
            <div>测试context</div>
    )
    }
};


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值