[React] Component(1)

DoDodo·2023년 2월 27일
0

React

목록 보기
1/5
post-thumbnail

Component

component: 리액트를 사용해서 앱의 인터페이스를 설계할 때 사용자가 볼 수 있는 요소는 여러가지 컴포넌트로 구성되어 있다.

컴포넌트를 선언하는 법
1. 함수형 컴포넌트
2. 클래스형 컴포넌트

  • 클래스형 컴포넌트는 함수형 컴포넌트와 달리 state 기능 및 라이프사이클 기능, 임의 메서드 정의 가능
  • 함수형 컴포넌트는 hook을 써서 state, 라이프사이클 api 사용 가능 클래스형 컴포넌트 보다 함수형 컴포넌트 + hook을 권장


Props & State

props : 컴포넌트 속성을 설정할 때 사용하는 요소

해당 컴포넌트를 불러와 사용하는 부모 컴포넌트에서 설정함

  1. 함수형 컴포넌트rsc에서의 비구조화 할당 문법
import React from 'react';

const MyComponent = {name, children} => { // 화살표 함수 사용
    return (
        <div>
           이름은 {name}<br/>
           {/* children = MyComponent 태그 사이에 들어가는 내용 */}
           children 값은 {children} 
        </div>
    );
};

export default MyComponent;
  1. 클래스형 컴포넌트rcc에서의 비구조화 할당 문법
import React, { Component } from 'react';

class mycomponent extends Component {
    render() {
        const {name, children} = this.props;
        return (
            <div>
                이름은 {name}<br/>
                children 값은 {children} 
            </div>
        );
    }
}

export default mycomponent;

비구조화 문법 : 값을 쉽게 추출할 수 있도록 해주는 문법


state : 컴포넌트 내부에서 바뀔 수 있는 값

컴포넌트에게 props는 읽기 전용

  1. 클래스형 컴포넌트에서의 state
import React, { Component } from 'react';

class Counter extends Component {
        state = {
            number : 0,
            fixedNumber: 0
        };
    render() {
        const {number} = this.state; //this.state 
        return (
            <div>
                <h1>{number}</h1>
                <h2>바뀌지 않는 값 {fixedNumber}</h2>
                <button 
                    onClick={() => {
                        this.setState({number: number+1}) //setState: 비동기적으로 update
                    }}>
                    +1
                </button>
            </div>
        );
    }
}

export default Counter;

  • state update 후 특정 작업을 하고 싶다면 setState의 두 번째 파라미터로 callback함수 사용
this.setState(
	{
	number: number +1
	},
	() => {
		console.log("ex");
	}
);
  1. 함수형 컴포넌트에서의 useState - hooks는 이후에 다룸
import React from 'react';

const say = () => {
    const [message, setMessage] = useState(''); // state의 초깃값 넣어줌
    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:'blue'}} onClick = {()=>setColor('blue')}>
                파란색
            </button>
        </div>
    );
};

export default say;


이벤트 핸들링

이벤트(event): 사용자가 웹 브라우저에서 DOM 요소(div, button, input, form, span)들과 상호 작용 하는 것

추후 useReducer, Hook 배우면 더 자세히 하겠삼

0개의 댓글