首頁  >  文章  >  web前端  >  如何在 React 中使用 Context

如何在 React 中使用 Context

王林
王林原創
2024-09-03 15:34:55651瀏覽

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 中使用 Context的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn