Java & Python

[React] - 이벤트 처리

토끼퉁 2023. 9. 12. 19:22

이벤트 처리 : 이벤트 핸들러를 JSX요소에 등록하여 사용한다.

클래스형 컴포넌트에서 이벤트 처리 : 메소드를 통해 이벤트 핸들러를 정의하고, JSX 요소에 연결한다.
this 키워드를 사용하려면 생성자 내부나 메서드 선언시 바인딩 해야한다.

class Example extends React.Component {
    constructor(props) {
        super(props)
        this.state = {count:0};

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState({count: this.state.count + 1});
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                {this.state.count}번
            </button>
        );
    }
}

 

함수형 컴포넌트에서 이벤트 처리 : 함수형 컴포넌트에서는 보통 화살표 함수로 이벤트 핸들러를 정의한다.

import React, {useState} from 'react';

function Example() {
    const[count, setCount] = useState(0);
    const handleClick = () => setCount(count+1);
    return (
        <button onClick={handleClick}>
            {count}번
        </button>
    )
}

'Java & Python' 카테고리의 다른 글

[React] - 생명주기  (0) 2023.09.12
[React] - Fragment  (0) 2023.09.12
[React] - 조건부 랜더링  (0) 2023.09.12
[React] - 폼 처리  (0) 2023.09.12
[React] - 바인딩(Binding)  (0) 2023.09.12