ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 23. Context API 를 사용한 전역 값 관리 - 리액트 입문 | 벨로퍼트
    Front-end/React.js 2020. 7. 5. 14:43
    반응형

     

    ContextSample 컴포넌트에서 text라는 pros에 "Good"을  GrandParent 컴포넌트에게 전달하면, GrandParent 컴포넌트에서 Parent 컴포넌트에게, 다시 Parent 컴포넌트에서 Child 컴포넌트에게 전달해서 화면에 "Good"이 보여진다.  

    * pros의 전달 과정 : ContextSample → GrandParent → Parent  → Child

     

    구조는 다음과 같다.

    /src/ContextSample.js : 

    import React from "react";
    
    function Child({ text }) {
        return <div>{text}</div>
    }
    
    function Parent({ text }) {
        return <Child text={text}></Child>
    }
    
    function GradParent({ text }) {
        return <Parent text={text}></Parent>
    }
    
    function ContextSample() {
        return <GradParent text={Good}></GradParent>
    }
    
    export default ContextSample;

    만약에 ContextSample 에서 Child 로 "Good" 이라는 text 를 바로 전달하고 싶다면 Context API를 사용하면 된다

    * pros의 전달 과정 : ContextSample → Child

     

    Context API를 사용하려면 상단에 createContext와 useContext라는 함수를 불러온다.

    /src/ContextSample.js :

    import React, { createContext, useContext, useState } from "react";
    
    const MyContext = createContext("Default Context")
    
    function Child() {
        const text = useContext(MyContext)
        return (
            <div>{text}</div>
        )
    }
    
    // ...
    
    function ContextSample() {
        const [ value, setValue ] = useState(true);
        return (
            <MyContext.Provider value="Good">
                <GradParent />
            </MyContext.Provider>
        )
    }
    
    export default ContextSample;

    ContextSample.js 맨 위에서 createContext() 함수를 이용해서 myContext 를 만든다. createContext 함수는 Context에서 사용할 기본값을 설정할 수 있다.

     

    그리고 Child 컴포넌트에서 MyContext에 있는 값을 불러와서 사용할 수 있다. useContext() 함수를 이용해서 MyContext의 값을 넣은 text 를 만든다. useContext 는 Context에 있는 값을 읽어와서 사용할 수 있는 React Hook 내장 함수이다.

     

    이렇게 입력하고 저장하면 Context의 value를 지정하지 않았기 때문에 기본값이 "Default Context"가 화면에 보여진다.

     

    만약에 MyContext의 값을 지정하고 싶다면 Context를 사용하는 맨 위에 있는 컴포넌트 즉, ContextSample에서 MyContext의 안에 있는 Provider라는 컴포넌트를 사용해야 한다.

     

    ContextSample에서 retrun에서 GrandParent를 <MyContext.Provider>로 감싸주고 value의 값을 Good으로 넣어준다. 그리고 GrandParent 의 text 속성을 지워준다.

     

    ※ Context는 다른 파일에서 작성해서 내보내면(export) 어떤 파일에서도 불러와서(import) 사용할 수 있는 장점이 있다.

     

    MyContext.Provider 라는 컴포넌트를 사용해서 value 값을 설정하면 이게 Context의 값이 된다.

    또한 Context의 값은 유동적으로 변할 수 있다.

    /src/ContextSample.js :

    //...
    
    function ContextSample() {
        const [ value, setValue ] = useState(true);
        return (
            <MyContext.Provider value={value ? "Good" : "Bad"}>
                <GradParent />
                <button onClick={() => {setValue(!value)}}>Click</button>
            </MyContext.Provider>
        )
    }

    useState 함수를 사용해서 value의 값이 true 이면 "Good"으로, false 이면 "Bad" 가 되는 조건문을 넣어준다.

     

    그리고 Button을 만들어서 클릭할 때마다 value의 값을 바꿔주는 onClick 함수를 만들어준다.

     

    반응형

    댓글

Luster Sun