리액트/컴포넌트

ch07.함수형 컴포넌트에서 UseState 사용하기

webmaster 2021. 7. 25. 23:40
728x90
  • 리액트 16.8 이후 버전부터는 함수형 컴포넌트에서 State를 사용할 수 있다.
  • 16.8 버젼 이후부터는 useState를 사용해서 state를 사용할 수 있다.
  • useState를 사용하기 위해서는 Hooks를 사용하게 되는데 Hooks중 한 가지가 useState다.

배열 비구조화 할당

  • Hooks를 알기 전에 알아야될 문법
  • 배열 안 값을 쉽게 추출 해줄수 있는 문법
  • const array = [1,2];
    const one = array[0];
    const two = array[1];
    // 배열 비구조화 할당
    const array = [1,2];
    const [one,two] = array;

UseState 사용하기

  • useState함수의 인자에 상태의 초깃값을 넣어준다.
  • useState에서는 반드시 객체 형태가 아니어도 상관이 없다.
  • 함수를 호출시 배열이 반환되는데 첫 번째 원소는 현재 상태, 두 번째 원소는 상태를 바꾸어 주는 함수(세타)이다.
  • 배열 비구조화 할당을 통해 이름을 자유롭게 줄 수 있다(message, setMessage로 현재는 설정)
  • say.js
    • import React, { useState } from "react";
      const Say = () => {
          const [message, setMessage] = useState('');//useState함수의 인자에는 상태의 초깃값을 넣어준다. 값을 형태는 자유(반드시 객체 아니여도 된다.)
                                                     // 함수 호출시 객체를 반환 첫번쨰 원소는 현재 상태, 두번쨰 원소는 상태를 바꾸어 주는 함수(세터함수)
                                                     // 배열 비구조화 할당을 통해 값을 자유롭게 정해줄 수 있다.
          const onClickEnter = () => {
              setMessage('안녕하세요!');
          }
          const onClickLeave = () => {
              setMessage('안녕히 가세요!');
          }
          return(
              <div>
                  <button onClick={onClickEnter}>입장</button>
                  <button onClick={onClickLeave}>퇴장</button>
                  <h1>{message}</h1>
              </div>
          )
      };
      export default Say;
  • App.js
    • import React, {Component} from 'react';
      import Say from './Say';
      const App = () =>{
        return <Say />;
      }
      export default App;
  • 실행결과
    • 결과

한 컴포넌트에서 useState 여러 번 사용하기

    • import React, { useState } from "react";
      const Say = () => {
        const [message, setMessage] = useState("");
        const onClickEnter = () => {
          setMessage("안녕하세요!");
        };
        const onClickLeave = () => {
          setMessage("안녕히 가세요!");
        };
        const [color, setColor] = useState("black");
        return (
          <div>
            <button onClick={onClickEnter}>입장</button>
            <button onClick={onClickLeave}>퇴장</button>
            <h1 style={{ color }}>{message}</h1>
            <button
              style={{ color: "red" }}
              onClick={() => {
                setColor("red");
              }}
            >
              빨간색
            </button>
            <button
              style={{ color: "green" }}
              onClick={() => {
                setColor("green");
              }}
            >
              초록색
            </button>
            <button
              style={{ color: "blue" }}
              onClick={() => {
                setColor("blue");
              }}
            >
              파란색
            </button>
          </div>
        );
      };
      
      export default Say;
    • 결과

 

 

728x90

'리액트 > 컴포넌트' 카테고리의 다른 글

ch08.State를 사용할 때 주의 사항  (0) 2021.07.26
ch06.클래스형 컴포넌트의 State(2)  (0) 2021.07.25
ch05.클래스형 컴포넌트의 State(1)  (0) 2021.07.25
ch04. State종류  (0) 2021.07.25
ch03.Props(2)  (0) 2021.07.23