React 기초-(2) 컴포넌트

김수민·2023년 1월 6일
0

React

목록 보기
2/17

컴포넌트

재사용이 가능한 각각의 독립적인 모듈
컴포넌트 프로그래밍을 하면 마치 레고 블럭처럼 이미 만들어진 컴포넌트들을 조합하여 화면을 구성한다.

웹 컴포넌트는 이러한 컴포넌트 기반 프로그래밍을 웹에서도 적용 할 수 있도록 W3C에서 새로 정한 규격이다.

함수형 컴포넌트

  • 선언이 편리
  • 메모리 자원 사용도가 클래스 형보다 작다.
  • 완성된 프로젝트의 파일크키가 작다.
import React from "react"
const Fun(){
	return(
    )
}
import React from "react"
const Fun=()=>{
	return(
    )
}

state 쓰기

import React, {useState} from 'react';

const Counter = () => {
	const [num, setNumber]= useState(0);
	const onIncrease =()=>{
		console.log('+1');
		setNumber(num+1);
	}
	const onDecrease =()=>{
		console.log('-1');
		setNumber(num-1);
	}
		return (
		<>
			<h2>{num}</h2>
			<button onClick={onIncrease}>+1</button>
			<button onClick={onDecrease}>-1</button>
		</>
	);
};

export default Counter;

클래스형 컴포넌트

  • {Component}가 import 되어있어야한다.
  • render() 함수를 필수적으로 요구한다.
import React, {Component} from "react"
class ClassComponent extends Component{
	render(
    	return(
        )
    ){}
}

으로 작성하고 export 된 곳에서

      <ClassComponent name="green"/>

과 같이 매개변수 값을 받아온다.

      <ClassComponent>blue</ClassComponent>

위의 blue값은 ClassComponent의 props.children이 된다.

state 쓰기

컴포넌트에서 state를 설정할 때는 constructor 메서드를 작성하여 설정한다.
이 때 반드시 super(props)를 호출해 주어야 한다.

	constructor(props){
		super(props);
		// state 초기값 설정
		this.state= {
		number: 0,
		}
	}

를 constructor를 선언하지 않고 선언하고자 한다면 아래와 같이 작성한다.

	state={
		number: 0
	}
import React, {Component} from "react";

class ClassCounter extends Component{
	state={
		number: 0
	}
	render(){
		const {number}= this.state;
		return(
			<div>
				<h2>{number}</h2>
				<button onClick={()=>{
					this.setState({number: number+1})
				}}>+1</button>
				<button onClick={()=>{
					this.setState({number: number-1})
				}}>-1</button>
			</div>
		)
	}
}

export default ClassCounter;

생성자 메소드인 constructor() 메소드를 사용하여 state 작성
❗ 클래스형 컴포넌트에서 constructor()를 작성할 때 반드시 super(props)를 호출해 주어야한다.
super(props)가 호출되면 현재 클래스형 컴포넌트가 상속받고 있는 리액트의 Component 클래스가 지닌 생성자 함수가 호출됨

Function 쓰기

this.func으로 호출한다. 여기서 func는 function의 name이다.


요소

props

default 값 주기

Component명.defaultProps={
	props명: "default값"
}

type 주기

import PropsTypes from "prop-types";
Component명.propTypes={
	props명: PropsTypes.string.isRequired
}

type 종류

  • array : 배열
  • bool : true / false
  • func : 함수
  • number : 숫자
  • string : 문자열
  • object : 객체
  • any : 모든 종류
profile
sumin0gig

0개의 댓글