React context/contextTypes

来源:互联网 发布:上海跳跃网络 编辑:程序博客网 时间:2024/06/09 21:36

本博客主要讲述一下,在开发工程总遇到的关于contextTypes/context的一些知识点。
通过context传递属性的方式可以大量减少 通过显式的通过 props 逐层传递属性的方式。这样可以减少组件之间的直接依赖关系。


(一)基本使用
基本使用方法,声明contextTypes,在函数或者render中通过this.context调用。如下:

// 常见的声明方式static contextTypes = {    router: React.PropTypes.object.isRequired,    location: React.PropTypes.object.isRequired  };// 可以在函数中引用handleToRoom(_bdroomid, crsstatus) {    this.context.router.push(`/workBench/searchResult/roomInfo?roomid=${_bdroomid}`);}// 也可以在render中引用render() {     return <div>{this.context.router}</div>;   }

(二)父子组件交流getChildContext
getChildContext 指定的传递给子组件的属性需要先通过 childContextTypes 来指定,不然会产生错误。

// 父组件Avar A = React.createClass({    childContextTypes: {         // 需要传递的变量需要在这里定义,否则会报错         name: React.PropTypes.string.isRequired    },    getChildContext: function() {         return {             name: "this is name",             erronMy: "this is erronMy"         };    },    render: function() {         return <B />;    }});// 子组件Bvar B = React.createClass({    contextTypes: {        erronMy: React.PropTypes.string.isRequired,        name: React.PropTypes.string.isRequired    },    render: function() {        return         <div>            {/* <div>{this.context.erronMy}</div> */}{/* 这样是会报错的 */}            <div>{this.context.name}</div>{/* 正确获取 */}        </div>    }});

一般开发都会通过–先state定义再props–来获取,相对来说,比较简单易懂。
而通过context传递属性的方式可以大量减少 通过显式的通过 props 逐层传递属性的方式。这样可以减少组件之间的直接依赖关系。

原创粉丝点击