如何在ReactJS中的子组件(兄弟姐妹)之间共享状态?

Ste*_*ffi 4 javascript reactjs gatsby

我想把状态传给兄弟姐妹甚至是祖父母.

我有3个组件.在里面Header,我有一个带有onClick功能的按钮,可以在里面切换下拉菜单Navigation.顺便说一下,我想通过相同的状态AnotherComponent.

如何将状态(如isDropdownOpened)传递HeaderNavigationAnotherComponent

<div>
     <Header />
       <Navigation />
        <div>
          <div>
             <div>
               <AnotherComponent />
             </div>
           </div>
        </div>
</div>
Run Code Online (Sandbox Code Playgroud)

Arn*_*ist 5

您有不同的方法来解决这种情况.

  • 将状态保持在顶部组件中并通过道具将其传递给子组件
  • 使用状态容器在组件之间保持和共享应用程序状态(例如https://redux.js.org/)
  • 使用新的React Context功能.Context提供了一种通过组件树传递数据的方法,而无需在每个级别手动传递props.


Arc*_*dio 5

这就是为什么开发了“React Hooks”(并被社区大肆宣传),但尚未在生产中使用它们的确切原因,它们仍处于早期开发阶段(alpha)并且它们的规范/实现可能会改变!

你的问题可以使用令人敬畏的“React Context” API来解决,它允许将数据传递给组件,无论它们在树中嵌套多深。要了解上下文,请阅读上面链接的大量文档。我只会在这里解释一个小而快速的例子:

  1. 创建上下文组件并导出使用者

应用程序.jsx

import React from "react";

// The initial value can be anything, e.g. primitives, object, function,
// components, whatever...
// Note that this is not required, but prevebents errors and can be used as
// fallback value.
const MyContext = React.createContext("anything");

// This component is the so called "consumer" that'll provide the values passed
// to the context component. This is not necessary, but simplifies the usage and
// hides the underlying implementation.
const MyContextConsumer = MyContext.Consumer;

const someData = { title: "Hello World" };

const App = ({ children }) => (
  <MyContext.Provider value={someData}>{children}</MyContext.Provider>
);

export { MyContextConsumer };
export default App;
Run Code Online (Sandbox Code Playgroud)
  1. 在任何组件中导入创建的使用者并使用提供的值

另一个组件.jsx

import React from "react";
import { MyContextConsumer } from "./App";

const AnotherComponent = () => (
  <div>
    <MyContextConsumer>{({ title }) => <h1>{title}</h1>}</MyContextConsumer>
  </div>
);

export default AnotherComponent;
Run Code Online (Sandbox Code Playgroud)
  1. 使用两个上下文组件渲染应用程序
import React from "react";

// The initial value can be anything, e.g. primitives, object, function,
// components, whatever...
// Note that this is not required, but prevebents errors and can be used as
// fallback value.
const MyContext = React.createContext("anything");

// This component is the so called "consumer" that'll provide the values passed
// to the context component. This is not necessary, but simplifies the usage and
// hides the underlying implementation.
const MyContextConsumer = MyContext.Consumer;

const someData = { title: "Hello World" };

const App = ({ children }) => (
  <MyContext.Provider value={someData}>{children}</MyContext.Provider>
);

export { MyContextConsumer };
export default App;
Run Code Online (Sandbox Code Playgroud)

该组件将呈现带有“Hello World”文本的 1 级标题。

编辑 stackoverflow-53648661-how-to-share-state-between-child-component-siblings-in-reactjs

  • app 和 anotherComponent 是父子关系,而不是兄弟姐妹。 (2认同)