[React] Component, props, state 구분하기

신치우·2022년 12월 17일
0

React

목록 보기
1/11

component 사용의 장점

  • 재사용 가능
  • 코드를 더 깔끔하게 만들어줌

1. React Component란?

  • React로 만들어진 앱을 이루는 최소한의 단위
  • Component는 props(data)를 입력받아 state(View) 상태에 따라 React Element를 출력
  • Component의 이름은 항상 대문자로 시작한다 (소문자로 시작하는 component는 DOM tag르 취급됨)
  • 객체 지향의 class와 instance랑 비슷함

2. React props

  • Property 를 줄여서 사용한 것
  • Component의 속성을 의미
  • Read-Only 임 ➡ 값을 변경할 수 없음

모든 react component는 그들의 Props에 관해서는 Pure 함수 같은 역할을 해야한다
➡ 모든 react component는 Props를 직접 바꿀수 없고, 같은 Props에 대해서는 항상 같은 결과를 보여줘야한다.

- component

function Comment(props){ <!-- Comment 라는 component를 생성하였고 그 안에 props를 넣음-->
    return(
        <div style={styles.wrapper}> 
            <div style={styles.imageContainer}>
                <img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png" style={styles.image} />
            </div>
        
            <div style={styles.contentContainer}>
                <span style={styles.nameText}>{props.name}</span>
                <span style={styles.commentText}>{props.comment}</span>
            </div>
        </div>
    );
}

- props

const comments =[
    {
        name : "1번",
        comment: "으아아아아아아아아아",
    },
    {
        name : "2번",
        comment: "호오오아ㅗ아와와와아이",
    },
    {
        name : "3번 ",
        comment: "으이이이이이이이이이이이",
    },
];

3. React State

  • React component의 변경 가능한 data
  • Rendering이나 data flow에 사용되는 값만 state에 포함되어야함
  • JS 객체
  • 모든 state는 constructor와 같이 사용됨
  • state는 직접 수정할 수 없다 (정확히는 직접 수정해서는 안된다) ➡ setState() 함수를 사용해서 수정해야함
constructor(props){
super(props);

this.state={};
}

4. Life Cycle

profile
하루에 집중을

0개의 댓글

관련 채용 정보