[리액트] 클래스 컴포넌트와 함수형 컴포넌트의 차이

휘루·2024년 4월 3일
0

리액트

목록 보기
5/5
import React, { Component } from 'react';

class Example extends Component {
	state = {
    	count: 0,
    };
    
    setcount(num) {
    	this.setState({
        	count: num,
        });
    }
    render() {
    	const { count } = this.state;
        return (
        	<div>
            	<div>
                	<p>You clicked {count} times</p>
                    <button onClick={() => {
                    	this.setCount(count + 1);
                    }}
                    >
                    	Click me!
                    </button>
                </div>
            </div>
        );
    }
}
export default Example;

└▷ 위의 내용은 클래스 컴포넌트입니다.

import React, { useState } from 'react';

function Example() {
	const [count, setCount] = useState(0);
    
    return (
    	<div>
        	<p>You clicked {count} times</p>
            <button onClick= {() => setcount(count + 1)}>
            	Click Me!
            </button>
        </div>
    );
}

export default Example;

└▷ 위의 내용은 함수형 컴포넌트입니다.
this와 render 없이도 상태값 접근이 가능합니다.

여러 state 변수 사용하기

하나의 컴포넌트 내부에서 state hook을 여러개 사용할 수도 있습니다.

import React, { useState } from 'react';

function App() {
	const [name, setName] = ('');
    const [age, setAge] = (35);
    const [coffee, setCoffee] = ('Latte');
}

export default App;
profile
반가워요

0개의 댓글