React でコンテキストを使用する方法

王林
リリース: 2024-09-03 15:34:55
オリジナル
628 人が閲覧しました

How to use Context in React

おかえりなさい、友達!


今日は useContext と呼ばれる React Hook の基本について説明します。 useContext は、useState をさらに一歩進んで、props を直接渡さずに子コンポーネントや孫コンポーネントに情報を渡すことができるグローバルのような State を作成する強力なツールです。

しかし、私は自分自身の先を行っています。
useState に詳しくない場合は、まず前の記事に飛んで読んでから、戻ってきて驚かれる準備をしてください。


「useState」の使用方法: https://dev.to/deborah/how-to-use-state-in-react-2pah

「useState」について理解したところで、「useContext」について詳しく見ていきましょう!

useContext とは何ですか?:

useContext は、グローバル スコープに配置する必要があるデータ (アプリケーション全体で誰かをログイン状態に保つユーザー名など) に最適ですが、これは、プロパティを子コンポーネントに渡します。
ただし、useContext を使用すると、props を直接渡さずにデータを渡すことができるため、複数の子コンポーネントからアクセスする必要があるデータや、アプリケーション全体で使用できるようにする必要があるデータに遭遇した場合に非常に役立ちます。

useContext を起動して実行するには、2 つの手順を実行する必要があります。まず、コンテキスト オブジェクト ('createContext') を作成する必要があります。次に、フック 'useContext' を使用してプロバイダ経由で値にアクセスする必要があります。 。

次の例は、useContext の概要とその使用方法をよりよく理解できるように簡略化されていますが、createContext は独自の別のファイルで宣言されることが多いことに注意してください。ただし、私は「Parent.js」を典型的な「App.js」ファイル(コンポーネント階層の最上位のコンポーネント)に例えています。 Parent.js では、すべての状態変数とそれらの状態変数を更新する関数を定義し、useEffect を使用してデータベースにフェッチしました。 Context の核となる概念をよりよく理解できるように、この説明を簡素化するために、独自のファイルを作成するのではなく、トップレベルのコンポーネントで createContext を宣言することにしました。

以上のことを踏まえて、最初の 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」に値を指定する必要もあります。ここで、子コンポーネントの「コンテキスト」で呼び出すすべての変数と関数を含むオブジェクトを渡します。

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>
);

ログイン後にコピー

プロパティを「value」内に置く限り、(「useState」の場合のように) プロパティを子コンポーネントに直接渡す必要がないことに注意してください。

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!