我正在阅读 Context > Parent-child coupling documentation的 react 。我无法从文档中得到什么父子耦合。通常这一行:
By passing down the relevant info in the Menu component, each MenuItem can communicate back to the containing Menu component.
代码是:
<Menu>
<MenuItem>aubergine</MenuItem>
<MenuItem>butternut squash</MenuItem>
<MenuItem>clementine</MenuItem>
</Menu>
最佳答案
如文章所述,React 中的数据流通常是通过将 props
从父组件传递到子组件来完成的。然而,在某些情况下,这种 prop
共享会变得乏味,在这些情况下,我们会使用 context
。
文档中的示例描述了如何连续线程化颜色 prop
最终会变得很烦人,但是在大多数情况下,您会在 prop 时使用
链比两层或三层要深得多。一个更好的例子可能是 Redux 中的 context
store
.
例如,那些使用 Redux 但未实现 react-redux 的人,必须从 context
访问 store
。现在,假设您有一个嵌套非常深的组件(孙子的孙子),它需要访问 store
- 那么,您可以:
- 通过
props
向下传递store
。然而,这意味着任何不需要访问store
的中间组件都必须将其作为prop
,以便将其传递给child
在它下面的某处确实需要它。添加批量和样板文件。 - 在高级组件中将
store
附加到context
。因此,任何在其内部指定contextTypes
的子组件都可以访问context
,因此也可以访问store
。通过这样做,我们不必担心用不必要的props
注入(inject)任何中间组件,因为我们可以访问context
。
请记住,context
是选择加入,因此只有明确指定 contextTypes
的组件才能访问 context
,如果上面定义了一个。
使用 Prop
Parent (Passes props with a store property)
|
+-> props -> Child
|
+-> props -> Grandchild
|
+-> props -> Great-Grandchild
|
+-> render() -> this.props.store.getState().message
使用上下文
Parent (Defines childContextTypes with store property)
|
+ -> Child
|
+ -> Grandchild
|
+ -> Great-Grandchild (Opts-in by defining contextTypes with a store property)
|
+-> render() -> this.context.store.getState().message
更新(引用由 this question 发布的 JMM ):
What API is it referring to?
我的理解是,这是指父组件在上下文中存储函数的能力,这些函数可以被子组件访问和调用,从而创建一个作用域 API。
What does it mean:
each MenuItem can communicate back to the containing Menu component
.
根据上述内容,如果在上下文中声明了一个函数,并且 MenuItem
通过 contextTypes
选择加入以获取该函数,则 MenuItem
可以调用它,从而与另一个组件通信。
关于javascript - React 中的父子耦合是什么,它与上下文有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057362/