React - Component

hanyoko·2023년 6월 22일

REACT

목록 보기
2/15
post-thumbnail

Component

재사용이 가능한 각각의 독립적인 모듈

  • 컴포넌트 프로그래밍을 하면 마치 레고 블럭처럼 이미 만들어진 컴포넌트들을 조합하여 화면을 구성한다.
  • 웹 컴포넌트는 이러한 컴포넌트 기반 프로그래밍을 웹에서도 적용 할 수 있도록 W3C에서 새로 정한 규격이다.

함수형 컴포넌트

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

//화살표 함수
import React from "react"
const Fun = () => {
	return(
    )
}

예시

import React from 'react';
//여기에 useState 사용할 수 없음
const TestComponent = () => {
    //여기에 작성
    return (
        <div>
            
        </div>
    );
};

export default TestComponent;

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;

Class형 컴포넌트

클래스형 컴포넌트는 render() 함수가 필수적이며 그 안에 보여주어야 할 jsx를 반환해줌

  • {Component}import 되어있어야한다.
  • ender() 함수를 필수적으로 요구한다.
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() 메소드를 사용하여 state 작성.
  • 클래스형 컴포넌트에서 constructor() 작성할 때 반드시 super(props)를 호출해주어야한다.
  • super(props)가 호출되면 현재 클래스형 컴포넌트가 상속받고 있는 리액트의 Component 클래스가 지닌 생성자 함수가 호출된다.
	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 클래스가 지닌 생성자 함수가 호출된다.

컴포넌트 작성

import React from 'react';

function Hello({name, message, isSpecial}){
    return (
    <>
        <div className='hello'>
        {/* 조건부렌더링 */}
        {isSpecial ? <b>*</b> : null }    
        {/* {isSpecial && <b>*</b>} 논리연산자 &&구문도 사용가능 */}
        {name}{message}</div>
        <p>재미있는 리액트</p>
    </>
    )
}
//기본값 설정
Hello.defaultProps = {
    name: "이름"
}

export default Hello;

Reactjs code snippets가 설치되어있다는 가정하에 rsc를 작성해도 위와 같은 형태의 함수를 작성해준다.


컴포넌트 호출

import './App.css';
import Hello from "./components/Hello";
import Wrapper from './components/Wrapper';

function App() {
  return (
    <div className="App">
      <Wrapper>
        <Hello name="green" message="안녕" isSpecial/> {/* 값을 주지 않으면 true가 기본값 */}
        <Hello name="blue" message="반가워" isSpecial/>
        <Hello name="yellow" message="재미있어" isSpecial={false}/>
        <Hello message="하하하"/>
      </Wrapper>
      
    </div>
  );
}

export default App;

App()이란, 다른 곳에서 호출되는 컴포넌트이다.
작성한 컴포넌트...<function name></function name>을 작성하면 호출 된다.


태그

두개 이상의 태그는 무조건 하나의 태그로 감싸져있어야 한다.

💡 return 안의 태그는 1개로 이루어져야한다. 1개의 태그 안에는 여러 태그가 들어갈 수 있다.

💡 return 안에 2개 이상의 태그를 작성 해야 한다면,

return(
  <>
    <div></div>
    <div></div>
  </>
)

와 같이 작성한다.


함수 호출

jsx안에서 js의 값을 사용할때에는 {}로 감싸서 호출한다.

const name="이름";
function Hello() {
	return(
		<div>{name}님 안녕하세요</div>

Function 쓰기

this.func으로 호출한다. 여기서 funcfunctionname이다.

0개의 댓글