본문 바로가기

프로그래밍&IT/React & CSS

Coding Apple, React 강좌 내용 정리.6 - map, for / props

React 강좌 내용 정리. 5 <저번에 이어서 같은 소스 기반으로 진행>

 

반복 사용 관련해서

 JSX 중괄호 내에 for 못 넣는다.

-> { map() } 사용해서 html 코드를 반복시킨다.

 

map() ?

array내의 모든 데이터에 똑같은 작업을 시켜주고 싶을 때

array.map(callbackFunction(currentValue, index, array), thisArg)

ex) var arr = [1,2,3];

    var newArray = arr.map( function(currentValue, index, array){

       return currentValue * 2;

    } );

   // newArray = [2,4,6]

결국 (유사) 반복문처럼 사용된다.

 

반복문 쓰는 법

{ 반복할 데이터.map( ()=> { return <HTML>} ) }

{
   글제목.map( function(){
      return <div>hello</div>
   } )
}

[ 결과 ]

 

for 반복문을 쓰고 싶다면?

  • 보통 함수 안에서 사용함
  • array에 HTML 추가하는 방식
  • 그리고 array를 return 한다.
function 항목들(){
  var arr = [];
  for (var i=0; i<3; i++){
    arr.push(<div>항목반복</div>);
  }
  return arr;
}

[ 결과 ]

props 문법

  1. App() {} 안에 있는 글제목 state를 (부모 컴포넌트)
  2. Modal(){} 안에서 쓰고 싶으면 (자식 컴포넌트)
  3. 자식 컴포넌트에 매개변수처럼 전달/전송하면 된다.

1. <자식컴포넌트 작명={state명} />

 {
    modal == true
    ? <Modal 작명={전송한 state}></Modal>
    : null
 }

 

2. 자식 컴포넌트에서 props 파라미터 입력 후 사용

// 부모에게 전달받은 props는 여기에 다 들어있다
function Modal(props ){
  return (
    <div className="modal">
        <h2>제목 {props.글제목[0]}</h2>
        <p>날짜</p>
        <p>상세내용</p>
    </div>
  )
}