[React] 컴포넌트

kbannie·2022년 10월 2일
0

리액트

목록 보기
2/3
post-thumbnail

📍 컴포넌트

리액트 컴포넌트란 리액트로 만들어진 앱을 이루는 최소한의 단위입니다. 컴포넌트를 선언하는 방식은 두 가지로 함수형 컴포넌트클래스형 컴포넌트입니다.

💡 클래스형 컴포넌트

1. 함수형 컴포넌트 vs 클래스형 컴포넌트

함수형 컴포넌트의 구조는 다음과 같습니다.

import React from ‘react‘;
import./App.css‘;


function App() {
  const name = ‘리액트‘;
  return <div className=“react“>{name}</div>;
}



export default App;

클래스형 컴포넌트의 구조는 다음과 같습니다. 클래스형 컴포넌트는 render 함수 안에 JSX를 반환해 줍니다.

import React, { Component } from 'react';
 
class App extends Component {
  render() {
    const name = 'react';
    return <div className="react">{name}</div>;
  }
}
 
export default App;

두 방식의 차이점은 클래스형 컴포넌트state 기능라이프사이클 기능을 사용할 수 있다는 것과 임의 메서드를 정의할 수 있다는 점입니다. 함수형 컴포넌트는 이를 구현할 수 없다는 점이었지만 리액트 v16.8 업데이트 후 Hooks라는 기능이 도입되면서 해결되었습니다.

2. 화살표 함수 (함수형 컴포넌트)

함수를 파라미터로 전달할 때 유용합니다. function(){ } 함수 선언 방식과 ()=>{ }를 비교해보면 다음과 같습니다.

setTimeout(function() {
  console.log('hello world');
}, 1000);
 
setTimeout(() => {
  console.log('hello world')
}), 1000);

화살표 함수는 값을 연산하여 바로 반환해야 할 때 사용하면 가독성을 높일 수 있습니다.

function twice(value) {
  return value * 2;
}
 
const triple = (value) => value * 3;

3. 모듈 내보내기 및 불러오기

//MyComponent.js
export default MyComponent;

위의 코드는 다른 파일에서 이 파일을 import할 때 위에서 선언한 MyComponent 클래스를 불러옵니다.

//App.js
import MyComponent from './Mycomponent';
const App=()=>{
  return <MyComponent/>;
};

위의 코드는 다른 파일에서 MyComponent 컴포넌트를 불러와서 사용하는 코드입니다.

💡 props

props는 properties를 줄인 표현으로 컴포넌트 속성을 설정할 때 사용하는 요소입니다. props 값은 해당 컴포넌트를 불러와 사용하는 부모 컴포넌트에서 설정할 수 있습니다.

1. defaultProps

//Mycomponent.js
const MyComponent = props => {
return <div>안녕하세요, 제 이름은 {props.name}입니다.</div>;
};

MyComponent.defaultProps = {
  name: '기본 이름'
};  //부모 컴포넌트에서 따로 name(props)을 지정해주지 않았을 때 
    //보여 줄 기본값을 설정해줍니다.
//App.js
const App = () => {
  return <MyComponent name="React" />;
  //return <MyComponent name="React" />;  
  //defaultProps를 사용할 때
};

2. 태그 사이에 내용을 보여 주는 children

//Mycomponent.js
const MyComponent = props => {
  return (
    <div>
      안녕하세요, 제 이름은 {props.name}입니다.<br /> 
      children 값은 {props.children}입니다.
    </div>
  );
};
//App.js
const App = () => {
  return <MyComponent name="React">리액트</MyComponent>;
};

브라우저에서 결과물은 다음과 같습니다.

안녕하세요, 제 이름은 React입니다.
children 값은 리액트입니다.

3. 비구조화 할당 문법을 통해 props 내부 값 추출하기

MyComponent에서 props 값을 조회할 때마다 props.name, props.children과 같이 props.이라는 키워드를 앞에 붙여 주고 있습니다. 작업을 편하게 하기 위해 할당 문법을 사용하여 내부 값을 바로 추출하는 방법입니다.

객체에서 값을 추출하는 문법을 비구조화 할당이라고 부릅니다.

//Mycomponent.js
const MyComponent = props => {
  const { name, children } = props;
  return (
    <div>
      안녕하세요, 제 이름은 {name}입니다. <br />
      children 값은 {children}
      입니다.
    </div>
  );
};

//파라미터 부분에서 비구조화 할당 문법을 사용할 수도 있습니다.
const MyComponent = ({ name, children }) => {
  return (
    <div>
      안녕하세요, 제 이름은 {name}입니다. <br />
      children 값은 {children}
      입니다.
    </div>
  );
};

4. propTypes와 isRequired

props의 타입을 지정할 때 propTypes을 사용합니다. import 구문을 사용하여 PropTypes를 불러와야 하며 선언 방법을 다음과 같습니다.

isRequired를 사용하여 필수 props로 지정할 수 있습니다.

//Mycomponent.js
import PropTypes from ‘prop-types‘;

const MyComponent = ({ name, favoriteNumber, children }) => {
  return (
    <div>
      안녕하세요, 제 이름은 {name}입니다. <br />
      children 값은 {children}입니다.<br />
      제가 좋아하는 숫자는 {favoriteNumber}입니다.  
    </div>
  );
};

MyComponent.propTypes = {
  name: PropTypes.string,
  //isRequired를 사용하여 필수 props로 지정할 수 있습니다.
  favoriteNumber: PropTypes.number.isRequired
};

💡 클래스형 컴포넌트의 state

state는 컴포넌트 내부에서 바뀔 수 있는 값을 의미합니다.

1. state 객체 안에 여러 값이 있을 때

state 객체 안에 두 개의 값을 설정해주었습니다. fixedNumber 값은 그대로 두고 nuber 값만 바꾸고 싶을 때는 this.setState 함수를 사용할 때 fixedNumber를 넣지 않으면 됩니다. this.setState 함수는 인자로 전달된 객체 안에 들어 있는 값만 바꿀 수 있기 때문입니다.

//Counter.js
import React, {Component} from 'react';

class Counter extends Component{
  //state를 설정할 때는 constructor 메서드를 작성
  constructor(props){
    super(props);
    //state의 초기값 설정하기
    this.state={
      number:0,
      fixedNumber:0
    };
  }
  render(){
    const {number,fixedNumber}=this.state; //state를 조회할 때는 this.state로 조회
    return(
      <div>
        <h1>{number}</h1>
        <h2>바뀌지 않는 값:{fixedNumber}</h2>
        <button
          //onClick을 통해 버튼이 클릭되었을 때 호출할 함수 지정
          onClick={()=>{
            //this.setState를 사용하여 state에 새로운 값을 넣음
            this.setState({number:number+1});
          }}
        >
          +1
        </button>
      </div>
    )
  }
}

export default Counter;



//App.js
import Counter from './Counter';

const App = () => {
  return <Counter />;
};

2. state를 constructor에서 꺼내기

위의 코드에서는 state의 초기값을 지정하기 위해 constructor 메서드를 선언해 주었습니다. 다음의 코드는 constructor 메서드를 선언하지 않고 state의 초기값을 지정하는 방법입니다.

//counter.js
class Counter extends Component {
  //constructor 메서드를 선언하지 않고 state 초기값 설정
  state = {
    number: 0,
    fixedNumber: 0
  };
  render() {
    const { number, fixedNumber } = this.state; // state를 조회할 때는 this.state로 조회합니다.
    return (...);
  }
}

3. this.setState가 끝난 후 특정 작업 실행하기

setState를 사용하여 값을 업데이트하고 난 다음에 특정 작업을 하고 싶을 때setState의 두 번째 파라미터로 콜백(callback) 함수를 등록하여 작업을 처리할 수 있습니다.

//counter.js -button
<button
  // onClick을 통해 버튼이 클릭되었을 때 호출할 함수를 지정합니다.
  onClick={() => {
    this.setState(
      {
        number: number + 1
      },
      () => {
        console.log(‘방금 setState가 호출되었습니다.);
        console.log(this.state);
      }
    );
  }}
>
  +1
</button>

💡 함수형 컴포넌트의 state

리액트 16.8 이후부터 함수현 컴포넌트에서도 Hooks 중 useState 함수를 사용하여 state를 사용할 수 있게 되었습니다.

1. 배열 비구조화 할당

배열 안에 들어 있는 값을 쉽게 추출할 수 있도록 해 주는 문법입니다.

const array = [1, 2];
const one = array[0];
const two = array[1];

//배열 비구조화 할당을 사용했을 때
const array = [1, 2];
const [one, two] = array;

2. useState 사용하기

useState 함수의 인자에 초깃값을 넣어 줄 때 반드시 객체일 필요가 없으며 값의 형태는 자유입니다.

//Say.js
const Say=()=>{
  const [message, setMessage]=useState("");
  //첫번째 원소는 현재 상태, 두번째 원소는 상태를 바꾸어 주는 함수입니다. -> 세터(setter)함수
  const onClickenter=()=>setMessage('안녕하세요!');
  const onClickLeave = () => setMessage('안녕히 가세요!');

  return (
    <div>
      <button onClick={onClickenter}>입장</button>
      <button onClick={onClickLeave}>퇴장</button>
      <h1>{message}</h1>
    </div>
  )

}


//App.js
import Say from './Say';
 
const App = () => {
  return <Say />;
};
profile
여행하는 데이터 사이언티스트🧙‍♂️

0개의 댓글