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 逐层传递属性的方式。这样可以减少组件之间的直接依赖关系。
阅读全文
0 0
- React context/contextTypes
- react中context学习
- React总结12:context
- react 上下文(Context)
- React数据传递---context
- React 中 context 的使用
- React高级指南(九)【Context】
- React Router context.router 未定义错误
- react-router 2.5 context undefiend replaceState deprecated
- React+DvaJs 之 Context与Props
- React之使用context传递数据
- 一招新的技能 React中的Context
- React 的数据载体:state、props、context
- react笔记-数据载体state/props/context
- React的数据载体state、props与context
- react的context更新而组件不更新的解决方案
- 教你如何优雅的使用React的context属性
- React Router 4 this.context 未定义错误 history undefined
- bash编程之 小技巧
- structs学习
- bash编程之 数组
- vim 基础 文件 命令
- bash编程之 函数
- React context/contextTypes
- idhttp解决中文乱码问题
- bash编程之 字符串操作
- MVC
- bash编程之 第六课作业
- Android总结篇系列:Android广播机制
- bash编程之 find文件查找工具
- C++ STL函数详解
- bash编程之 crontab 定时任务