728x90

React 엘리먼트에서 이벤트를 처리하는 방식은 DOM 엘리먼트에서 이벤트를 처리 방식과 매우 유사하다.
- React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용한다.
- JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달한다.

- DOM 요소에만 이벤트 설정이 가능하다. div, button, input, form, ul, li, span 등

- React Component 에는 이벤트 설정이 불가능하다.

 

Event Handler 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="theme-color" content="#000000"/>
    <title>React App Sample</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
    class Component extends React.Component {
        constructor(props) {
            super(props);
            this.state = {count: 0};
            this.click = this.click.bind(this);
        }
 
        render() {
            return (
                <div>
                    <h3>{this.props.item}</h3>
                    <p>{this.state.count}</p>
                    <button onClick={this.click}>클릭</button>
                </div>
            );
        }
 
        click() {
            console.log("clicked");
            this.setState((state) => ({
                ...state,
                count: state.count + 1,
            }));
        }
    }
 
    // 사용
    ReactDOM.render(
        <Component item={"Front-End : React"}/>,
        document.querySelector('#root')
    );
</script>
</body>
</html>

 

여기에 버튼의 명칭이 ON, OFF 가 번갈아 가면서 나오도록 하는 걸 추가해보자.

<script type="text/babel">
    class Component extends React.Component {
        constructor(props) {
            super(props);
            this.state = {count: 0, isToggleOn: true};
            this.click = this.click.bind(this);
        }
 
        click() {
            console.log("clicked");
            this.setState((state) => ({
                ...state,
                count: state.count + 1,
                isToggleOn: !state.isToggleOn
            }));
        }
 
        render() {
            return (
                <div>
                    <h3>{this.props.item}</h3>
                    <p>{this.state.count}</p>
                    <button onClick={this.click}>{this.state.isToggleOn ? 'ON' : 'OFF'}</button>
                </div>
            );
        }
 
    }
 
    // 사용
    ReactDOM.render(
        <Component item={"React Event Handler"}/>,
        document.getElementById('root')
    );
</script>

 

 

 

 

 

 

 

 

728x90

'React > React' 카테고리의 다른 글

React Query String  (0) 2022.06.08
React Router v6  (0) 2022.06.07
React useState  (0) 2022.06.04
React 값 전달(부모 → 자식, 자식 → 부모)  (0) 2022.06.03
React Component 만들기  (0) 2022.05.28
블로그 이미지

Link2Me

,