[React] Props 와 State

2022. 8. 2. 17:44·Front-End/React

[React] Props 와 State

Props란?

  • Props는 Properties의 줄임말이다.
  • 상속하는 부모 컴포넌트로부터 자녀 컴포넌트에 데이터등을 전달하는 방법
  • Props는 읽기 전용(immutable)으로 자녀 컴포넌트 입장에서는 변하지 않는다. (변경하고 싶으면 부모 컴포넌트에서 state를 변경 시켜야한다.)

Props의 사용

//App.js
const App = () => {
  return <Text text='Hello world!'/>

//Text.js
const Text = ({text}) => {
  return <div>{text}</div>
}

위의 코드는 부모 컴포넌트(App)에서 자식 컴포넌트(Text)에 Props를 사용해서 “Hello world!” 라는 문자열 데이터를 전달했다.

여러개의 Props 와 defaultProps

  • 부모 컴포넌트에서 여러개의 props를 넘겨줄 수 있다.
  • props 내부의 값을 조회 할 때, 비구조화 할당 문법을 사용하면 간결하게 작성가능하다.
  • 컴포넌트에 props를 지정하지 않았을 때, 기본값을 설정하고 싶으면 defaultProps 값을 설정한다.

App.js

import React from 'react';
import Hello from './Hello';
import './App.css';

function App() {
    return (
        <>
        <Text text="Hello world!" color="red"/>
        <Text color="pink"/>
        </>
    );
}

export default App;

Text.js

import React from 'react';

function Hello({ color, name }) {
    return <div style={{ color }}>{text}</div>
}

Hello.defaultProps = {
    text: '기본값 텍스트 입니다.'
}

export default Hello;

컴포넌트 태그 사이에 넣은 값 조회 - props.children

App.js

import React from 'react';
import Hello from './Hello';
import './App.css';
import Wrapper from "./wrapper";

function App() {
    return (
        <Wrapper>
            <Text text="Hello world!" color="red"/>
            <Text color="pink"/>
        </Wrapper>
    );
}

export default App;

Wrapper.js

import React from 'react';

function Wrapper({children}) {
    const style = {
        border: '2px solid black',
        padding: '16px',
    };
    return (
        <div style={style}>
            {children}
        </div>
    )
}

export default Wrapper;

State란?

  • 컴포넌트 내부에서 데이터를 전달하는 방법
  • State는 변경 가능(mutable)이며, State가 변하면 re-render 된다.
  • 변경하기 위해서는 useState에서 반환하는 Set 함수를 사용해야한다.

State의 사용

State 선언

const [변수명, Set함수명] = useState (데이터 초기값);
  • State를 사용하기 위해 useState라는 훅을 사용
  • useState는 State변수의 초기값을 매개변수로 전달하여 호출하고, 배열을 반환하게 된다.
  • 반환된 배열에는 초기값이 할당된 변수와 해당 변수를 수정하기위한 Setter가 포함되어 있다.

Counter.js

import React, { useState } from 'react';

function Counter() {
  const [number, setNumber] = useState(0);

  const onIncrease = () => {
    setNumber(number + 1);
  }

  const onDecrease = () => {
    setNumber(number - 1);
  }

  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}

export default Counter;
  • +와- 를 누르면 값이 1씩 올라가고, 내려가는 코드이다.
  • useState를 이용해서 count를 State선언 후, set함수를 이용해서 1씩 증가시켰다.

App.js

import React from 'react';
import './App.css';
import Counter from "./Counter";

function App() {
    return (
        <Counter/>
    );
}

export default App;

함수형 업데이트

  • 기존값을 업데이트 할때, 함수를 등록하여 값을 업데이트 할 수 있다.
  • 함수형 업데이트는 컴포넌트 최적화를 할 때 주로 사용한다
import React, { useState } from 'react';

function Counter() {
  const [number, setNumber] = useState(0);

  const onIncrease = () => {
    setNumber(prevNumber => prevNumber + 1);
  }

  const onDecrease = () => {
    setNumber(prevNumber => prevNumber - 1);
  }

  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}

export default Counter;

참조

https://reactjs.org/docs/components-and-props.html

https://reactjs.org/docs/state-and-lifecycle.html

https://react.vlpt.us/basic/07-useState.html

 

7. useState 를 통해 컴포넌트에서 바뀌는 값 관리하기 · GitBook

7. useState 를 통해 컴포넌트에서 바뀌는 값 관리하기 지금까지 우리가 리액트 컴포넌트를 만들 때는, 동적인 부분이 하나도 없었습니다. 값이 바뀌는 일이 없었죠. 이번에는 컴포넌트에서 보여줘

react.vlpt.us

 

반응형
'Front-End/React' 카테고리의 다른 글
  • [React] useCallback, useMemo, React.memo를 이용한 최적화 및 차이점
  • [React] 리액트에서 불변성을 지키는 이유
  • [React] Hooks란?
  • [React] 가상돔
LightSource
LightSource
어제보단 발전한 오늘의 나를 위한 블로그
    반응형
  • LightSource
    LightSourceCoder
    LightSource
  • 전체
    오늘
    어제
    • 분류 전체보기 (152)
      • Git (4)
      • Language (6)
        • Java (6)
      • Back-End (63)
        • Spring Boot (4)
        • MyBatis (1)
        • Oracle (1)
        • PL SQL (3)
        • JPA (26)
        • Spring Data JPA (5)
        • Spring MVC (8)
        • Spring (12)
        • Spring Security (2)
        • Redis (1)
      • Front-End (38)
        • 아이오닉 (2)
        • JSP (7)
        • JavaScript (4)
        • React (16)
        • TypeScript (3)
        • Angular (6)
      • AWS (1)
      • CI & CD (1)
      • 개발지식 (13)
        • 네트워크 (9)
        • CS 지식 (4)
      • 데이터모델링 (2)
      • Tool (1)
      • 프로젝트 (5)
      • 독후감 (2)
      • 잡생각 (0)
      • 면접 준비 (1)
      • 알고리즘 (14)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    배요소열추가
    리액트
    react
    배열요소수정
    배열요소삭제
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
LightSource
[React] Props 와 State
상단으로

티스토리툴바