ReactJS - 将道具(状态)传递给 children of children

ReactJS - Passing props (state) to children of children

我有一个简短的问题。 如何将状态传递给 children of children?

如果 parent 有某种状态,在 ES6 中最好的方法是将这种状态传递给它的直接 child,而不是直接传递给 child child.

我附上了布局图片。

Main app - is the main component that consists of Header, Sidebar, Content Area.

Sidebar consists of - Sidebar Items.

Content Area consists of - Content Items.

主要问题

如何通过单击 边栏项目 更新 内容区域 中的组件?

请注意,此布局有 6 个组件(应用程序、页眉、边栏、内容区域、边栏项、内容项)。

图片

如果您以更复杂的方式处理状态,可能值得考虑使用 Redux 来处理整个应用程序的状态。

这样,您可以使用 'connect' 将状态映射到道具,并根据需要在组件之间传递状态。查看 here 了解有关如何实施它的更多信息。

唯一可以做到这一点的 React 方法是将状态和道具从 parent 直接传递到 child。如果 grandchild 需要来自 grandparent 的 state 或 props,parent 必须继续向下传递它直到到达 grandchild。 React 是单向的;仅从 parent 到 child。

因此在您的情况下,grandparent(主应用程序)将包含一些状态,这些状态将传递给 children(边栏和内容区域)。例如,从 parent 组件,您可以像这样将状态传递给 child:

<Sidebar someState={this.state.someParentState} />
<ContentArea someState={this.state.someParentState} />

当边栏中的状态发生变化时(在您的示例中为单击),它将反映在 grandparent(主应用程序)上。由于同一状态在多个组件(内容区)之间共享,因此将更新具有该状态的每个组件。

现在,如果您在想,"wow wouldn't this get messy if there are multiple children, with children that have children?"。答案是,"yes, it can!" 这就是状态容器(Redux、Flux、MobX)的用武之地。这就是你使用它的原因:

  1. 直接向任何 children 插入状态。比如不一定要从parent到child,可以从grandparent直接到grandchild。在 Redux 中,您只需使用 connectmapStateToProps 函数将部分状态连接到单个组件作为 props 即可。
  2. 状态在大型应用程序中更易于维护和处理。尝试通过向下、向下、向下传递状态来仅使用 React 创建 Facebook。
  3. 将状态与组件分开。由于 React 适用于 "building UI interfaces",因此将状态与表示分开是明智的。对于简单的情况,没关系,但随着应用程序变得越来越复杂,就不是这样了。

考虑 Redux(最流行的状态容器)的以下资源: