react 上下文(Context)

来源:互联网 发布:淘宝电脑键盘手写图片 编辑:程序博客网 时间:2024/06/05 18:51
注意: 从 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>    )    }};


原创粉丝点击