介绍如何使用 React 的 context
Using context and childContext in React
在 React 使用 context 和 childContext
When working with React in a deeply nested hierarchy, often times you will find yourself in a situation where you need to pass down props from the parent as is to the children and the grandchildren. Although passing down properties is great, but writing code in such a manner encourages relying on memory to pass down the necessary props, and that’s not really a good use of your brain.Fortunately, React provides a way to make this task easier.
在操作 React 中深层嵌套的层次结构时,当你需要从父组件获取 props 传递到子组件时,通常你需要找到自己所在的位置。尽管传递 properties 是好的做法,但在写代码时却要依靠记忆传递所需要的 props,这对大脑来说不怎么友好。幸运的是,React 提供了一种方式使得这些工作简单完成。
React has something called as Child contexts that allows a parent element to specify a context — aka a set of properties — which can be accessed from all of its children and grandchildren via the this.context object.
React 有一些叫做 Child context 的东西,允许父元素指定一个 context - 等于设置一个属性 - 它的所有 children 和 grandchildren 都可以通过 this.context
对象访问它的属性。
There are 2 aspects to how you would go about implementing this in your code.
在代码实现需要处理两方面。
1.In the parent, the getChildContext method is used to return an object that is passed own as the child context. The prop types of all the keys in this object must also be defined in the childContextTypes property of the parent.
2.Any child that needs to consume the properties passed down from its parents must whitelist the properties it wants to access via the ‘contextTypes’ property.
Here’s an example of how this works
1.在父组件,getChildContext 方法返回一个对象,这个对象把自己传给 child context。这个对象中所有的 key 的 prop types 也必须在父组件的 childContextType 属性中定义。
2.任何 child 想访问从 parent 传递过来的 properties,都需要通过将 properties 添加到 contextTypes 属性进行访问。
这里是一段它们如何工作的代码:
1 |
|
One may argue that this makes the code a bit more verbose, because now you end up creating an additional key contextTypes on every child component. However, the reality is that you can specify the ‘contextTypes’ property on a mixin. That way you can avoid rewriting the whitelisting boilerplate code by simply using the mixin on all the child components that need to access those properties from its context.
有人可能会说这使得代码更复杂,因为现在要在每个子组件额外的添加 contextTypes
属性。但是,其实你可以把 contextTypes 属性的代码放到 mixin。通过简单的在所有子组件使用 mixin 可以避免重写白名单的代码,这样所有子组件都可以通过 context 访问父组件的属性了。