Step by Step

React Study(2) - 리액트를 다루는 기술 3장 본문

React

React Study(2) - 리액트를 다루는 기술 3장

짤진이 2023. 1. 25. 19:10
반응형

#3장
3.1 클래스형 컴포넌트
컴포넌트
기본 컴포넌트 Todo Template, TodoInput, TodoList, TodoItem

컴포넌트를 선언하는 방식은 두 가지이다.
함수 컴포넌트, 클래스형 컴포넌트
차이점은 클래스형 컴포넌트의 경우 state 기능 및 라이프 사이클 기능 사용이 가능, 임의 메서드 정의가능

3.2 첫 컴포넌트 생성

class App extends Component{
  render(){
    const name = 'react';
    return <div className="react">{name}</div>
  }
}


클래스형 컴포넌트에서는 render함수가 꼭 있어야하고 반환해야함.
힘수 컴포넌트의 장점
클래스형 컴포넌트보다 선언하기가 편하다.
메모리 자원도 클래스형 컴포넌트보다 덜 사용.
프로젝트를 완성하여 빌드한 후 배포할 때도 결과물의 파일 크기가 작음.
함수 컴포넌트의 단점
state와 라이프사이클 API 사용이 불가능했다. 이젠 아님.

3.3 props
props는 properties를 줄인 표현으로 컴포넌트 속성을 설정할 떄 사용하는 요소

태그 사이의 내용을 보여 주는 children

App.js

const App = () =>{
  return <MyComponent>리액트</MyComponent>;
};

3.3.4
컴포넌트 태그 사이의 내용이 children

<MyComponent.js>

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


출력 값 => 안녕하세요, 제 이름은 기본 이름입니다. <br> children 값은 리액트입니다.

3.3.5
MyComponent의 props 값을 조회할 때마다 props.name, props.children 을 붙이는 데 수정
name값과 children의 값을 더 짧은 코드로 사용 가능
비 구조화 할당, 구조 분해 문법이라고 불림.

<MyComponent.js>

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

MyComponent.defaultProps = {
    name : "기본 이름"
};



3.3.6
propTypes를 통한 props 검증
import PropTypes from 'prop-types'; 을 불러오고

MyComponent.propTypes ={
    name:PropTypes.string
};
이렇게 설정해 주면 name 값은 무조건 문자열 형태로 전달 해야 한다는 것을 의미함

문자열이 아닐 때


3.3.6.1
isRequired를 사용하여 필수 propTypes 설정
propTypes를 지정하지 않았을 때 경고 메시지를 띄워 주는 작업
뒤에 isRequired를 붙여 주면 된다.

<App.js>

const App = () =>{
  return <MyComponent name='React' favoriteNumber={3}>리액트</MyComponent>;
};

<MyComponent.js>
import PropTypes from 'prop-types';

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

MyComponent.defaultProps = {
    name : "기본 이름"
};

MyComponent.propTypes ={
    name:PropTypes.string,
    favoriteNumber:PropTypes.number.isRequired
};

export default MyComponent;



3.3.6.2
더 많은 propTypes 종류들
array : 배열
arrayOf : 특정 PropType로 이루어진 배열
bool : true , false
func : 함수
number : 숫자
object : 객체
string : 문자열
symbol : ES6, Symbol
node : 렌더링할 수 있는 모든 것
instanceOf : 특정클래스의 인스턴스
oneOf : 주어진 배열 요소 중 값 하나
oneOfType : 주어진 배열 안의 종류 중 하나
objectOf : 객체의 모든 키 값이 인자로 주어진 PropType인 객체
shape : 주어진 스키마를 가진 객체
any : 아무 종류

3.3.7
클래스형 컴포넌트에서 props 사용하기

<MyComponent.js>

import PropTypes from 'prop-types';
import {Component} from 'react';


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

MyComponent.defaultProps = {
    name : "기본 이름"
};

MyComponent.propTypes ={
    name:PropTypes.string,
    favoriteNumber:PropTypes.number.isRequired
};

export default MyComponent;



3.4
state는 컴포넌트 내부에서 바뀔 수 있는 값
props는 컴포넌트가 사용되는 과정에서 부모 컴포넌트가 설정하는 값이면 컴포넌트 자신은 해당 props를 읽기 전용으로만 사용
props를 바꾸려면 부모 컴포넌트에서 바꾸어 주어야함
두 가지 종류의 state가 있는데 하나는 클래스형 컴포넌트가 지니고 있는 state이고 하나는 함수 컴포넌트에서 useState라는 함수를 통해 사용하는 state이다.

3.4.1 클래스형 컴포넌트의 state
<Counter.js>

import {Component} from 'react';

class Counter extends Component{
    constructor(props) {
        super(props);
        this.state={
            number:0
        
    };
}
render() {
    const {number} = this.state;
    return (
        <div>
            <h1>{number}</h1>
            <button 
                //onClick을 통해 버튼이 클릭되었을 때 호출할 함수를 지정합니다.
                onClick={() =>{
                this.setState({number:number+1});
            }}
        
        >
            +1
            </button>
        </div>
    );
    }
}


<코드 분석>

export default Counter;

constructor(props) {
        super(props);
        this.state={
            number:0
        
    };
}


컴포넌트에 state를 설정할 때는 constructor 메서드를 작성하여 설정합니다.
클래스형 컴포넌트에서 constructor를 작성할 때는 반드시 super(props)를 호출해야 한다.
컴포넌트의 state는 객체 형식이어야 하므로 this.state값에 초깃값을 설정한다.

render() {
    const {number} = this.state; //state를 조회할 때는 this.state
    return (
        <div>
            <h1>{number}</h1>
            <button //button안에 onClick값을 props로 넣었는데 이는 버튼이 클릭될 때 호출시킬 함수를 설정할 수 있게 해줌.
                //onClick을 통해 버튼이 클릭되었을 때 호출할 함수를 지정합니다.
                onClick={() =>{//이벤트로 설정할 함수를 넣어 줄 때는 화살표 함수 문법을 사용하여 넣어주어야 한다.
                this.setState({number:number+1});
            }}
        
        >
            +1
            </button>
        </div>
    );
    }
}


3.4.2
useState 함수의 인자에는 상태의 초깃값을 넣어줍니다.

<Say.js>

import {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;

반응형