패스트 캠퍼스 MGS 3기 - 5월 16일(Rendering, onClick)

JY·2022년 5월 16일
0

1. Rendering


  • 조건부 렌더링
    • 렌더 시 무시되는 값
  • 루프 활용 렌더링
  • key의 역할


조건부 렌더링


실습

true, false, null, undefined 이러한 값들은 화면에 렌더되지 않는다. 이를 {true ? <div></div> : undefined} 이런 식으로 활용할 수 있다.

return (
  <>
    <div>{[false, null, undefined, true]}</div>
    <div>{false}</div>
    <div>{null}</div>
    <div>{undefined}</div>
    <div>{true}</div>
  </>
)

루프 활용 렌더링



key의 역할


  • 불필요한 렌더를 줄일 수 있다. 변화가 일어났을 때, key값을 비교해서 원래 있던 것은 다시 렌더링 하지 않는다.
  • keyrops으로 전달되지 않는다. (props 이름을 key로 정의하는 것을 피하자! key는 예약이므로 전달이 안 된다.)
  • key 값이 없어도 사실 동작에는 문제 없지만, 최적화를 위해서 부여하는 것이다. (성능 향상)
    • 1개의 아이템이 추가되었을 때, 500개의 아이템을 다시 렌더링 하는 것은 굉장히 비효율적이다.


실습


  1. map()을 이용해서 1~100까지 버튼을 출력
  2. 10의 배수이면 버튼을 출력하지 않는 조건 걸기
  3. 7의 배수는 버튼에 7의 배수라고 출력하는 조건 걸기
const arr = Array.from(Array(100), (_, i) => {return(i+1)});

function App() {
  return (
    <div>
      {
        arr.map((num) => {
          if(num % 10 === 0) return null;
          if(num % 7 === 0) {
            num = "7의 배수"
          }
          return(<button>{num}</button>)
        })
      }
    </div>
  );
}
// key를 줄 경우

const arr = Array.from(Array(100), (_, i) => {return(i+1)});

function App() {
  return (
    <div>
      {
        arr.map((num) => {
          if(num % 10 === 0) return null
          if(num % 7 === 0) {
            // num = "7의 배수"
            return (<button key={num}>7의 배수</button>)
          }
          return(<button key={num}>{num}</button>)
        })
      }
    </div>
  );
}

2. Event Handling


  • onclick이 아닌 onClick으로 작성한다.
  • 실행될 코드를 적는 게 아닌, 실행될 함수를 전달해야 한다.
  • onClick={실행될 함수}
    • 함수에 리턴문이 없는 경우 undefined를 리턴한다.

실습

const arr = Array.from(Array(100), (_, i) => {return(i+1)});

const handleClickButton = (num) => () => {
  alert(num)
}

function App() {
  return (
    <div>
      {
        arr.map((num) => {
          return(<button key={num} onClick={handleClickButton(num)} >{num}</button>)
        })
      }
    </div>
  );
}

🤔 closure
handleClick = item1을 받는 함수 (return값은 item2를 받는 함수)
바깥에 있는 함수까지 재사용 할 수 있다.


복습

다음 코드에서 App 컴포넌트에는 key를 추가하고, 하단 이미지와 같은 결과가 출력되도록 Card 컴포넌트를 채워넣자.

import React from 'react';

const users =  [{
  name: 'kim',
  id: 5,
}, {
  name: 'hello',
  id: 6,
}, {
  name: 'jin',
  id: 7,
}, {
  name: 'hi',
  id: 10,
}, {
  name: 'yellow',
  id: 8,
}];

const Card = (props) => {
  return (
    <div>
    </div>
  );
}

const App = () => {
  return (
    <>
      {users.map((user) => <Card user={user} />)}
    </>
  );
};

export default App;


👉 정답

const Card = (props) => {
  return (
    <div>
      id: {props.user.id}
      <br />
      name: {props.user.name}
    </div>
  );
}

const App = () => {
  return (
    <>
      {users.map((user) => <Card user={user} key={user.id} />)}
    </>
  );
};



👉 오늘 강의의 중요한 결론

  • keyprops로 전달되지 않는다.
  • 리액트 환경의 이벤트 객체와 자바스크립트 이벤트 객체는 다르게 생겼다..!





더 공부해야 할 것

in Javascirpt

  • 고차함수
  • closure
  • curring
profile
🙋‍♀️

0개의 댓글