날아라김지원
Published 2022. 1. 16. 17:31
React context API React

props와달리

 

계속 props->props해서 안쓰고 좀더 다른방식으로 사용할 수 있는 방법

 

컴포넌트 > 컴포넌트 > 컴포넌트 이렇게 있을때 겉에 감싸주기만 하면 사용할 수 있다.

 

import React,{useContext, useState} from 'react';

useContext를 가져와서

 

let 재고context = React.createContext()

function App() {

  let [shoes,shoes변경] = useState(Data)
  let [재고,재고변경] = useState([10,11,12])

.........

이와같이 context를 만들어준다

 

그리고 아래와같이

 

context.Provider로 감싸주고, 

 

안에 useState에서 선언한 변수를 넣어준다.

 

 <재고context.Provider  value = {재고}>
    {/* 이안에서는 자유롭게 재고 사용가능 */}
  <div className="row">          
      {
        shoes.map((a,i)=>{
          return <Card shoes={shoes[i]} i={i} ></Card>
        })
      }

      

  </div>
  </재고context.Provider>
function Card(props){

  let 재고 = useContext(재고context)
  // Hook임, 그리고 뒤에는 범위 이름 넣으면됨

  return(
    <>
    <div className="col-md-4"> 
    <img src={'https://codingapple1.github.io/shop/shoes'+(props.i+1)+'.jpg'} width="100%"></img>
     <h4>{props.shoes.title}</h4>
    <p>{props.shoes.content} & {props.shoes.price}</p></div>
    {/* {재고[props.i]} */}
    </>
  )
}

그리고 이와같이 사용할 컴포넌트안에 선언해서 useContext를 이용해사용해주면된다.

 

그리고 다른 파일에 export,import해서 사용하는 컴포넌트에도 마찬가지로 사용해 줄 수 있다.

 

하지만 그냥 props나 리덕스를 더 사용할거같다. 우선 알아두도록하자. 쓰게되면 다시 찾아서 사용하기로

'React' 카테고리의 다른 글

React Redux 1  (0) 2022.01.17
React Tab UI,(react-transition-group)  (0) 2022.01.16
React 배포(build)  (0) 2022.01.16
React Component중첩, props, state  (0) 2022.01.15
React Ajax  (0) 2022.01.15
profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!