react中context学习
来源:互联网 发布:jq的数组点击显示隐藏 编辑:程序博客网 时间:2024/06/06 08:35
简介:在React中,数据可以以流的形式自上而下的传递,每当你使用一个组件的时候,你可以看到组件的props属性会自上而下的传递。但是,在某些情况下,我们不想通过父组件的props属性一级一级的往下传递,我们希望在某一级子组件中,直接得到上N级父组件中props中的值。
1.一般情况下通过props传值的情况
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
我们来分析一下这段代码,大致的组件分为3级:
顶层MessageLists——>Message一级子类——>Button底层子类
我们来看从父组件到子组件的值的传递情况:
(1)text:
我们可以看到,在顶层组件MessageLists中的值,传递到一级子组件Message中,并在此组件中被使用。
(2)color:
再看props中的color的传递情况,在顶层组件MessageLists中的值,先传递到一级子组件Message中,
在传递到二级子组件Button中,最后在二级子组件中被使用。
综上:这就是一般在React中,所使用的通过props属性,在父组件与子组件中进行值传递。
2.如何利用React中的Context来进行值的越级传递。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
上述代码,我们实现了通过React的Context实现了值——color的越级传递。我们来分析一下上述的方法。
(1)首先在顶层组件中:
- 1
- 2
- 3
- 1
- 2
- 3
定义了顶层组件所拥有的子类context对象——该顶层组件所拥有的的子类context对象为color,且必须为字符串。
然后通过getChildText方法,来给子context对象的属性赋值:
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
这样就完成了顶层组件中,context对象的赋值。
(2)越级传递,因为color属性只在最底层使用
我们来看color属性的越级传递,因为color属性,在一级子组件Message中并没有直接用到,因此我们可以
直接传递到最底层(越级),在Button组件中使用。
首先Button组件中,再次声明了所接受到的context的子组件color的类型,声明必须为字符串:
- 1
- 2
- 3
- 1
- 2
- 3
然后可以通过this.context.color这种方式调用:
- 1
- 2
- 3
- 1
- 2
- 3
综上:这样,我们发现通过Context,我们就能实现值得越级传递。
- react中context学习
- React 中 context 的使用
- React context/contextTypes
- React总结12:context
- react 上下文(Context)
- React数据传递---context
- React高级指南(九)【Context】
- Demo中学习React-入门学习
- react学习之路(2.2)-----数据传递(props(子传父级),context)
- React学习笔记----如何在html页面中使用react
- React学习中几个注意点
- react-native 学习中网站及博客
- React学习中几个注意点
- React Native学习中之modal
- React学习-业务中模块的拆分
- Android中,Context,什么是Context?
- Android中,Context,什么是Context?
- 【Spring学习笔记】Spring中Application Context和Servlet Context的区别
- gitHub存放页面
- 方法和函数区别
- Java多线程/并发03、实现定时任务的3种方法
- guava中的ListenableFuture
- tomcat不解压war包问题
- react中context学习
- DUBBO研究与学习三:Dubbo+zookeeper安装
- 理解 Python 中的 *args 和 **kwargs
- Android NDK开发之从环境搭建到Demo级十步流
- 什么是广播
- Hbase -0.98伪分布式安装与配置
- Struts2接受的参数乱码
- apache 配置vhost
- 数据结构与算法之时间复杂度(笔记)