这就是为什么开发了“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;
- 在任何组件中导入创建的使用者并使用提供的值
另一个组件.jsx
import React from "react";
import { MyContextConsumer } from "./App";
const AnotherComponent = () => (
<div>
<MyContextConsumer>{({ title }) => <h1>{title}</h1>}</MyContextConsumer>
</div>
);
export default AnotherComponent;
- 使用两个上下文组件呈现应用程序
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import AnotherComponent from "./AnotherComponent";
const Root = () => (
<App>
<AnotherComponent />
</App>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<Root />, rootElement);
该组件将呈现带有“Hello World”文本的 1 级标题。
