首页  >  文章  >  web前端  >  如何在 React 中使用上下文

如何在 React 中使用上下文

王林
王林原创
2024-09-03 15:34:55580浏览

How to use Context in React

欢迎回来,朋友们!


今天我们将回顾名为 useContext 的 React Hook 的基础知识。 useContext 是一个强大的工具,它比 useState 更进一步,创建了一个类似全局的 State,可以将信息传递给子组件和孙组件,而无需直接传递 props。

但我有点超前了。
如果你不熟悉 useState,请先跳过去阅读我之前的文章,然后再回来准备大吃一惊!


如何使用‘useState’:https://dev.to/deborah/how-to-use-state-in-react-2pah

现在您已经了解了“useState”,让我们深入了解“useContext”!

什么是 useContext?:

useContext 非常适合需要放置在全局范围内的数据(例如使某人在整个应用程序中保持登录状态的用户名),但它并不是最终的快捷方式将 props 传递给子组件。
然而,useContext 允许我们在不直接传递 props 的情况下传递数据,因此当我们遇到需要由多个子组件访问或在整个应用程序中可用的数据时,useContext 非常有用。

为了让 useContext 启动并运行,我们需要执行两个步骤:首先,我们需要创建一个上下文对象('createContext'),然后我们需要使用钩子 'useContext' 通过提供者访问该值。

以下示例已进行简化,以便让您更好地了解 useContext 的含义以及如何使用它,但您应该注意 createContext 通常在其自己的单独文件中声明。然而,我将“Parent.js”比作典型的“App.js”文件(组件层次结构顶部的组件)。 Parent.js 是我定义所有状态变量、更新这些状态变量的函数,并使用 useEffect 获取数据库的地方。我选择在顶级组件中声明 createContext,而不是创建自己的文件,以简化此说明,以便您可以更好地理解 Context 的核心概念。

话虽如此,让我们从头开始:createContext!

1.我们需要做的第一件事是声明并导出一个名为“Context”的变量,稍后我们将在子组件中使用该变量[我们现在正在创建一个变量,以便使我们的代码更简单,因此我们可以将稍后访问其中的值(数据)]:

export Context = React.createContext();

‘Context’是通过调用‘createContext’创建的上下文对象。上下文对象包含一个名为 Provider 的组件,我们现在可以调用该组件,然后传递我们想要保留在“全局”级别的变量和函数。

2. 使用“Context”变量,现在让我们跳到 return 语句中的 JSX。在这里,我们将调用“Context”并将其包装在开始标签(尖括号)中,并像这样调用 Provider:


return(
    <Context.Provider >
        // Other JSX & the child components we want to hand Context to.

    </Context.Provider>
);

为了完成'Context.Provider',我们还需要为'Provider'提供一个值。我们将在这里传递一个带有所有变量和函数的对象,我们将在子组件中使用“Context”调用这些变量和函数:

return(
    <Context.Provider value ={{ example, setExample, handleExample }}>
        // Other JSX & the child components we want to hand Context to.

    </Context.Provider>
);

非常重要的是要注意,我们需要将所有将使用变量和函数的子组件放在标签之间。例如:

return(
    <Context.Provider value ={{ example, setExample, handleExample }}>
        <Child />
    <Components />
    <Go />
    <Here />
    </Context.Provider>
);

请注意,我们不需要将任何 props 直接传递给子组件(就像我们使用“useState”一样),只要我们将 props 放在“value”中即可。

现在我们已经使用了 createContext 并将所有全局项传递给“Context.Provider”,我们准备好继续讨论子组件并了解如何使用“Context”。

3. Let’s go onto a child component which (for the sake of this example) is housed in the file "Child.js". As life is with coding: if you want to use something, you need to import it. Let’s go ahead and get ‘Context’ from where we declared it in ‘Parent.js’ so we can use it in this child component (‘Child.js’):

import Context from ‘./Parent.js’;

4. Now that we have access to ‘Context’ in the child component, we now need to import 'useContext' into the file so we can pass 'Context' to it (more on that shortly):

import React, { useContext } from ‘react’;
import Context from ‘./Parent.js’;

5. Great! Now let’s use 'useContext'. First we need to declare a variable to use 'useContext' with. We’ll do this inside the component in a similar fashion to how we would declare useState:

import React, { useContext } from ‘react’;
import Context from ‘./Parent.js’;

function Child(){
    const { example, setExample } = useContext(Context)

    // The rest of our code

In this code we are using curly braces {} to denote destructuring assignment. That's a fancy way of saying we are able to call multiple variables and functions stored in Context. We are also passing ‘Context’ to 'useContext' so we can access the values defined in Context.Provider (which we declared in ‘Parent.js’).



6. Believe it or not, you are all set! You can now use the context values in your code just like you would normally use State. For example:

const expId = example.id;

or

setExample(newExample);

Let’s Recap:

Congratulations! You now have all the tools to get started with createContext and useContext. You understand that useContext allows you to create something of a ‘global state' that can pass variables and functions to components without passing props directly through child components.

We also delved into the six steps required to get context working in your applications. You are now ready to begin coding with createContext and useContext, but in case you ever need a quick-start guide, here you go:


In your parent component, declare and export a variable called 'Context' using 'createContext':

export const Context = React.createContext();

In the parent component’s JSX, wrap all child components that need access to context in Context.Proivder, and pass any variables/functions inside an object:

<Context.Provider value={{ example, setExample, handleExample }}>
   //Child components
</Context.Provider>

In you child component, import 'useContext':

import React, { useContext } from ‘react’;

Also import ‘Context’ from the parent component:

import Context from “./Parent.js’;

Then use useContext and pass it your ‘Context’ variable:

const { example, handleExample } = useContext(Context);

Finally, use the context you now have access to (in our examples above this would be 'example' and 'handleExample') however you need to in the child component.

Well done! And until next time, happy coding!

One last note, if you would like to delve deeper into this subject, here are the official documentation resources I also referenced while learning useContext and writing this blog:


Official Documentation:
https://react.dev/reference/react/createContext


Legacy Official Documentation, still somewhat helpful for understanding useContext:
https://legacy.reactjs.org/docs/context.html

以上是如何在 React 中使用上下文的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn