Context
被翻译为上下文,在编程领域,这是一个常常会接触到的概念,React中也有。html
在React的官方文档中,Context
被归类为高级部分(Advanced),属于React的高级API,但官方并不建议在稳定版的App中使用Context。react
The vast majority of applications do not need to use content.web
If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.编程
不过,这并不是意味着咱们不须要关注Context
。事实上,不少优秀的React组件都经过Context来完成本身的功能,好比react-redux的<Provider />
,就是经过Context
提供一个全局态的store
,拖拽组件react-dnd,经过Context
在组件中分发DOM的Drag和Drop事件,路由组件react-router经过Context
管理路由状态等等。在React组件开发中,若是用好Context
,能够让你的组件变得强大,并且灵活。redux
今天就想跟你们聊一聊,我在开发当中,所认识到的这个Context
,以及我是如何使用它来进行组件开发的。react-router
注:本文中全部提到的App皆指Web端App。app
React文档官网并未对Context
给出“是什么”的定义,更可能是描述使用的Context
的场景,以及如何使用Context
。ide
官网对于使用Context
的场景是这样描述的:this
In Some Cases, you want to pass data through the component tree without having to pass the props down manuallys at every level. you can do this directly in React with the powerful "context" API.翻译
简单说就是,当你不想在组件树中经过逐层传递props
或者state
的方式来传递数据时,能够使用Context
来实现跨层级的组件数据传递。
使用props或者state传递数据,数据自顶下流。
使用Context
,能够跨越组件进行数据传递。
参考:https://www.jianshu.com/p/eba2b76b290b
官网:https://react-1251415695.cos-website.ap-chengdu.myqcloud.com/docs/context.html