>  기사  >  웹 프론트엔드  >  React에서 컨텍스트를 사용하는 방법

React에서 컨텍스트를 사용하는 방법

王林
王林원래의
2024-09-03 15:34:55582검색

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를 시작하고 실행하려면 두 단계를 수행해야 합니다. 먼저 컨텍스트 객체('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를 'value' 안에 넣는 한 ('useState'와 마찬가지로) props를 하위 구성 요소에 직접 전달할 필요가 없습니다.

이제 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으로 문의하세요.