javascript의 확장된 문법
React “엘리먼트(element)” 를 생성
props
컴포넌트에 전달되는 단일 객체
순수함수처럼 동작해야한다. props 자체를 수정해서는 안된다.
컴포넌트 합성
여러개의 컴포넌트를 모아서 사용할 수 있다.
컴포넌트 추출
여러 곳에 사용되거나 복잡한 경우 컴포넌트를 추출해 사용한다.
재사용이 가능해진다.
컴포넌트의 상태
자신의 출력 값을 변경
class componenet
state LifeCycle
componentDidMount()
functional component
Hook으로 관리할 수 있다.
useState
useEffect
컴포넌트를 class 또는 함수로 정의할 수 있다.
class component와 functional component 똑같이 동작되게 할 수 있다.
state를 직접 수정하지 말기
state 업데이트는 비동기적
React 컴포넌트 class를 정의하려면 React.Component를 상속받아야 한다.
컴포넌트 생성.
컴포넌트의 인스턴스가 생성되어 DOM 상에 삽입될 때에 아래의 순서대로 호출된다.
constructor()
render()
componenetDidMount()
Funtional component에서 useState -> render -> useEffect 와 흐름이 비슷하다
props나 state가 업데이트 되었을 때
render()
componenetDidUpdate()
컴포넌트가 DOM 상에서 제거될 때 호출
constructor
state 초기화 및 메서드 바인딩
componentDidMount
DOM 노드 초기화 및 데이터 fetch
comoponentWillUnmount
타이머 제거 및 요청 취소 및 구독 해제
Functional Component
hook으로 대부분 구현 가능
state에 props를 복사하면 안된다.
React 엘리먼트에서 이벤트를 처리하는 방식은 DOM 엘리먼트에서 이벤트를 처리하는 방식과 매우 유사하다.
React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용
JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달
<button onclick="activateLasers()">
Activate Lasers
</button>
<button onClick={activateLasers}>
Activate Lasers
</button>
Capture > target > Bubble
(top-down) ........ (Bottom-up)
import React from 'react'
function UserGreeting(props) {
// name이 있어야 느낌표 3개
// count가 있어야 문장 보이기
return <h1>hi our user {props.name && `${props.name}!!!`}! {props.count ? `${props.count} times visit` : null}</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up~!</h1>;
}
function Greeting(props) {
return props.isLoggedIn ? <UserGreeting name='bang' count={1} /> : <GuestGreeting />;
}
export default function Condition() {
const isLoggedIn = true;
return (
<div>
<Greeting isLoggedIn={isLoggedIn}/>
</div>
)
}
-> 개별 요소 순회할 때 형제끼리 고유한 key 값이 없으면 react는 default key로 index를 사용한다.
하지만 이 경우 unique 하지 않기 때문에 warning
이 뜨고, key 값을 주도록 하자.
* key는 형제 사이에서만! 고유하면 된다. 자식 형제끼리만 구분할 수 있으면 된다.
Key는 식별하기 위한 용도만으로 사용한다.
Key는 props가 아니기 때문에 넘겨지지 않는다. props.key
자식이 알 수 없음. 만약 사용하고 싶으면 직접 props.id
로 만들어서 줘야함.
input의 value를 state로 관리한다.
하나의 핸들러를 가지고 다중 입력 가능 -> event.target.name, event.target.type ... 으로 관리할 수도 있다.
form element 자체의 내부 상태를 활용한다.