Ste*_*ffi 4 javascript reactjs gatsby
我想把状态传给兄弟姐妹甚至是祖父母.
我有3个组件.在里面Header,我有一个带有onClick功能的按钮,可以在里面切换下拉菜单Navigation.顺便说一下,我想通过相同的状态AnotherComponent.
如何将状态(如isDropdownOpened)传递Header给Navigation和AnotherComponent?
<div>
<Header />
<Navigation />
<div>
<div>
<div>
<AnotherComponent />
</div>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
您有不同的方法来解决这种情况.
这就是为什么开发了“React Hooks”(并被社区大肆宣传),但尚未在生产中使用它们的确切原因,它们仍处于早期开发阶段(alpha)并且它们的规范/实现可能会改变!
你的问题可以使用令人敬畏的“React Context” API来解决,它允许将数据传递给组件,无论它们在树中嵌套多深。要了解上下文,请阅读上面链接的大量文档。我只会在这里解释一个小而快速的例子:
应用程序.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)
另一个组件.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)
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 级标题。
| 归档时间: |
|
| 查看次数: |
1816 次 |
| 最近记录: |